谁能解释我从这个简单程序中得到的输出std::map
。请注意,我插入p
进入地图,但没有q
但它说它找到了它们,而且还说地图中只有 1 个元素!
#include <map>
#include <iostream>
struct screenPoint {
float x = 0, y = 0;
screenPoint(float x_, float y_): x{x_}, y{y_}{}
};
bool operator<(const screenPoint& left, const screenPoint& right){
return left.x<right.x&&left.y<right.y;
}
std::map<screenPoint, float> positions;
int main(int argc, const char * argv[]) {
auto p = screenPoint(1,2);
auto q = screenPoint(2,1);
positions.emplace(p,3);
auto f = positions.find(p);
auto g = positions.find(q);
if (f == positions.end()){
std::cout << "f not found";
} else {
std::cout << "f found";
}
std::cout << std::endl;
if (g == positions.end()){
std::cout << "g not found";
} else {
std::cout << "g found";
}
std::cout << std::endl;
std::cout << "number elements: " << positions.size() << "\n";
return 0;
}
Output:
f found
g found
number elements: 1
在这种情况下,问题在于您定义比较函子的方式。这两个元素,p
, and q
, 有相同的x
and y
,只是颠倒了。
你的逻辑检查x
其中一个小于另一个,并且y
是。这永远不能评估为true
,对于这些输入。
试试这个片段:
int main()
{
auto p = screenPoint(1,2);
auto q = screenPoint(2,1);
std::cout << std::boolalpha << (p < q) << " " << (q < p) << std::endl;
}
它将打印出来
false false
So p
不小于q
, and q
不小于p
。就地图而言,这使它们等效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)