[英]How do I compare a std::function's target with a member function's address?
[英]How do I compare the std::map's body members?
我在stl :: map中基于键A保留结构B。 我正在编写代码,该代码基于从旧值到上述地图主体的任何成员的任何更新,我将打印一个警报。
我不知道该怎么做。 我研究了互联网。 任何帮助,将不胜感激。 谢谢。
如果定义了用作键和值的类型,并且定义了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;
}
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;
}
第一个实现会更快,但是再次,它假定地图的顺序相同。
您应该迭代地图并进行比较:
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
}
}
确保您的地图是否包含自定义对象,比较运算符已正确实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.