Benyamin Jane
Benyamin Jane

Reputation: 407

Comparing two multimap objects in c++

i need to compare two multimap objects to find out whether they are equal or not

i know by using std::equal we can compare two vector object equality but is it possible to use this algorithm for comparing to multimap objects?

typedef std::multimap<std::string, std::string> HeaderMap;
HeaderMap _map,_secMap;


_map.insert(HeaderMap::value_type("A", "a"));
_map.insert(HeaderMap::value_type("B", "b"));

_secMap.insert(HeaderMap::value_type("A", "a"));
_secMap.insert(HeaderMap::value_type("B", "b"));



**std::equal(_map.begin(),_map.end(),_secMap.begin()); // is this true?**

if above code snippet is not true, how i can compare two multimap objects?(i don't ant to iterate objects and compare keys and values one by one) thanks

Upvotes: 1

Views: 1264

Answers (1)

juanchopanza
juanchopanza

Reputation: 227418

You can compare them with operator==:

map_ == secMap_;

This will internally compare elements one by one until the first unequal one is found. There is no way of avoiding that. Here is a working example:

#include <map>
#include <string>
#include <iostream>

int main()
{
  typedef std::multimap<std::string, std::string> HeaderMap;

  HeaderMap m1, m2, m3;

  m1.insert(HeaderMap::value_type("A", "a"));
  m1.insert(HeaderMap::value_type("B", "b"));

  m2.insert(HeaderMap::value_type("A", "a"));
  m2.insert(HeaderMap::value_type("B", "b"));

  m3.insert(HeaderMap::value_type("A", "a"));
  m3.insert(HeaderMap::value_type("B", "b"));
  m3.insert(HeaderMap::value_type("C", "c"));


  std::cout << std::boolalpha;
  std::cout << (m1==m2) << " " << (m1==m3) << std::endl;    
}

Output:

true false

Bear in mind that names with leading underscores are reserved for the implementation so you should not use them.

Upvotes: 2

Related Questions