how to compare two maps

Feb 14, 2010 at 7:58pm
I need to compare two maps to see if they are equal. The two maps use strings as keys but the values can be of different types. For example. one map can be <string, int> and the other map can be <string, map<string,int>>. Can anyone suggest a neat solution.
Feb 14, 2010 at 8:04pm
How would you compare an int with a map<string,int>?
Feb 14, 2010 at 8:08pm
To have two maps that are equal, shouldn't their type also be the same?
Feb 14, 2010 at 8:17pm
If the value types are different, the function should return false. The value type can be primitive types like int, float, or classes like maps, vectors, lists. And the function should be like a recursion.
Feb 14, 2010 at 8:36pm
I don't see what good recursion would do you.

Here's something

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template <typename T, typename U>
bool CompareMaps(const map<string,T>& l, const map<string,U>& r)
{
    return false;  // different types
}

template <typename T>
bool CompareMaps(const map<string,T>& l, const map<string,T>& r)
{
  // same types, proceed to compare maps here

  if(l.size() != r.size())
    return false;  // differing sizes, they are not the same

  typename map<string,T>::const_iterator i, j;
  for(i = l.begin(), j = r.begin(); i != l.end(); ++i, ++j)
  {
    if(*i != *j)
      return false;
  }

  return true;
}


this assumes std::pair has a != operator overload, which I didn't check. If it doesn't you'll have to do this:

1
2
if(i->first != j->first)  return false;
if(i->second != j->second)  return false;


EDIT: I'm also not sure if you need that typename there. I'm still fuzzy on where you need it.
Last edited on Feb 14, 2010 at 8:40pm
Feb 15, 2010 at 12:38pm
One thing to think about is: if two maps have different comparators or different allocators but
identical elements, are they still equal? (map has 4 template parameters).

std::map<> has operator== defined already (though it is only callable if all 4 template parameters
are the same).

typename is needed in a template function or template class which uses the syntax "something :: something"
where one of the somethings is directly dependent upon one of the template parameters. So yes, you need
it on line 15.

Topic archived. No new replies allowed.