为什么没有找到这个std::map键?
Why is this std::map key not getting found?
我以前问过一个类似的问题,现在我有一个相关的问题。下面,输出是"not found",打印的元素数是2。
行positions.emplace(r,q);
清楚地插入了元素并且映射大小是正确的,那么为什么没有找到r
?p
是找到(在这个例子中没有记录)。
#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;
}
您的operator<
不是严格弱排序。例如,您有p<q
和q<p
。这意味着任何map
操作的未定义行为。
operator<
(忽略nan)的一种方法是:
bool operator<(const screenPoint& left, const screenPoint& right) {
return left.x < right.x ||
( left.x == right.x && left.y < right.y );
}
您的比较运算符
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
,如
bool operator<(const screenPoint& left, const screenPoint& right){
return std::tie(left.x, left.y) < std::tie(right.x, right.y);
}
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 使用一个考虑到std::map中键值的滚动或换行的键
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- C++如何创建 std::map
- 从其他容器中移动构造"std::map"
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 使用重载 [] 运算符返回 std::map() 的可赋值
- std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
- C++ 使用枚举类对象分配 std::map 值
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- std::map:当元素不可默认构造时创建/替换元素
- Arduino编译器和STL:使用std::vector和std::map