任何人都可以解释我从这个简单的程序使用的输出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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
f found
g found
number elements: 1
Run Code Online (Sandbox Code Playgroud)
问题在于您在这种情况下定义比较仿函数的方式.这两个元素,p以及q具有相同的x和y,正好相反.你的逻辑检查x一个小于另一个的那个,以及ys.true对于这些输入,这永远无法评估.
试试这个片段:
int main()
{
auto p = screenPoint(1,2);
auto q = screenPoint(2,1);
std::cout << std::boolalpha << (p < q) << " " << (q < p) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
它会打印出来
false false
Run Code Online (Sandbox Code Playgroud)
所以p不小于q,q也不小于p.就地图而言,这使它们等同.