开发者

How do I compare the std::map's body members?

I am keeping a structure B based on a key A in a stl::map. I am writing code that based on any updates to any member of the body of the above map from the old values, I wi开发者_开发百科ll print an alert.

I have no idea hoew to do that. I have researched the internet. Any help would be appreciated. Thanks.


If the types used as key and values have operator== defined, the simplest expensive solution is keeping a backup of the map, and then comparing both maps:

std::map<key,value> the_map;
std::map<key,value> test_copy; // hidden from the rest of the code
                               // copied from the_map on particular instants
bool map_has_changed() {
   return the_map != test_copy;
}


struct foo 
{
   // foo members
};

bool isEqual(const std::map<int,foo>& map1, const std::map<int,foo>& map2)
{
   std::map<int,foo>::const_iterator itr1, itr2;
   for (itr1 = map1.begin(), itr2 = map2.begin(); itr1 != map1.end(), itr2 != map2.end(); itr1++, itr2++)
   {
      if (itr1->first != itr2->first) return false;
      if (!isEqual(itr1->second, itr2->second)) return false;
   }
   return true;
}

bool isEqual(const foo& f1, const foo& f2)
{
   // some implementation that checks if f1 and f2 are equal
}

The downside of this implementation is that it assumes that the members of each map are in the same order (which means they are inserted into in the same order). If they could be a different order, then you will need to do something like this for the std::map isEqual:

bool isEqual(const std::map<int,foo>& map1, const std::map<int,foo>& map2)
{
   std::map<int,foo>::const_iterator itr, temp;
   for (itr = map1.begin(); itr != map1.end(); itr++)
   {
      temp = map2.find(itr->first);
      if (!temp) return false;
      if (!isEqual(itr->second, temp->second)) return false;
   }
   return true;
}

The first implementation will be faster, but again, it assumes that the map is in the same order.


You should iterate the map and do a comparison:

std::map<int, std::string> my_map;
int someint = 2;
std::string mystr = "tony";
std::map<int, std::string>::iterator it;

for (it = my_map.begin(); it != my_map.end() it++)
{
    if (it->first == someint) 
      { 
          //do something 
      }

    if (it->second == mystr) 
       { 
         // do something else 
       }
}

Make sure if your map contains custom objects that comparison operators are properly implemented.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜