我如何比较std :: map的正文成员?

时间:2011-04-13 10:40:16

标签: c++ stl map comparison compare

我基于stl :: map中的键A保留结构B.我正在编写代码,基于对旧值的上述地图的任何成员的任何更新,我将打印一个警报。

我不知道如何做到这一点。我研究过互联网。任何帮助,将不胜感激。感谢。

3 个答案:

答案 0 :(得分:3)

如果用作键的值和值已定义operator==,最简单的昂贵解决方案是保留地图的备份,然后比较两个地图:

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;
}

答案 1 :(得分:1)

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
}

此实现的缺点是它假定每个映射的成员处于相同的顺序(这意味着它们以相同的顺序插入)。如果它们可能是不同的顺序,那么你需要为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;
}

第一个实现会更快,但同样,它假定地图的顺序相同。

答案 2 :(得分:0)

您应该迭代地图并进行比较:

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 
       }
}

确保您的地图包含正确实施比较运算符的自定义对象。