为什么不能找到这个std :: map键? [英] Why is this std::map key not getting found?
本文介绍了为什么不能找到这个std :: map键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我之前曾问过类似问题,现在我已经相关问题。下面,输出为未找到,打印的元素数为2。
I asked a similar question once before and now I have a related problem. Below, the output is "not found" and the number of elements printed is 2.
positions.emplace(r,q)
清楚地插入元素,映射大小是正确的,为什么找不到 r
? p 是。
The line positions.emplace(r,q);
clearly inserts the element and the map size is correct, so why is r
not found? p
is found (not logged in this example).
#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, screenPoint> positions;
int main(int argc, const char * argv[]) {
auto p = screenPoint(593,271.5);
auto q = screenPoint(595.5,269.5);
auto r = screenPoint(599,267);
positions.emplace(p,q);
positions.emplace(r,q);
auto f = positions.find(r);
if (f == positions.end()){
std::cout << "not found";
} else {
std::cout << "found";
}
std::cout << std::endl;
std::cout << "number elements: " << positions.size() << "\n";
return 0;
}
推荐答案
>
Your comparison operator
bool operator<(const screenPoint& left, const screenPoint& right){
return left.x<right.x||left.y<right.y;
}
不正确。您需要使用if语句,如果 x
的等于返回,如果 left.y
小于 right.y
否则返回 left.x< right.x
。或使用 std :: tie
like
Is incorrect. You need to use an if statement and if the x
's are equal return if left.y
is less than right.y
otherwise return left.x < right.x
. or use std::tie
like
bool operator<(const screenPoint& left, const screenPoint& right){
return std::tie(left.x, left.y) < std::tie(right.x, right.y);
}
这篇关于为什么不能找到这个std :: map键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文