std :: map的用途是什么? [英] What is this use of std::map doing?
问题描述
任何人都可以使用 std :: map
解释我从这个简单程序中获得的输出.请注意,我在地图中插入了 p
,但没有插入 q
,但它表示找到了这两个元素,而且还说地图中只有1个元素!
Can anyone explain the output I am getting from this simple program using std::map
. Note that I insert p
into the map, but not q
yet it says it found them both, but also says there is only 1 element in the map!
#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;
}
输出:
f found
g found
number elements: 1
推荐答案
在这种情况下,问题出在定义比较函子的方式上. p
和 q
这两个元素具有相同的 x
和 y
,只是倒置了.您的逻辑将检查其中一个的 x
是否小于另一个,以及 y
s.对于这些输入,这永远不能评估为 true
.
The problem is with the way you defined the comparison functor, in this case. The two elements, p
, and q
, have the same x
and y
, just inverted.
Your logic checks that the x
of one is less than that of the other, as well as the y
s. This can never evaluate to true
, for these inputs.
尝试以下代码段:
int main()
{
auto p = screenPoint(1,2);
auto q = screenPoint(2,1);
std::cout << std::boolalpha << (p < q) << " " << (q < p) << std::endl;
}
它将打印出
false false
因此 p
不小于 q
,并且 q
不小于 p
.就地图而言,这使它们等效.
So p
is not less than q
, and q
is not less than p
. As far as the map is concerned, that makes them equivalent.
这篇关于std :: map的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!