为什么没有找到这个std::map键?

Why is this std::map key not getting found?

本文关键字:std map 为什么      更新时间:2023-10-16

我以前问过一个类似的问题,现在我有一个相关的问题。下面,输出是"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<qq<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);
}