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

时间:2016-09-30 17:16:37

标签: c++

之前我问了一次similar question,现在我遇到了一个相关的问题。下面,输出“未找到”,打印的元素数量为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;
}

2 个答案:

答案 0 :(得分:3)

您的plyr不是严格的弱排序。例如,您有operator<p<q。这意味着任何q<p操作的未定义行为。

提供有效map,忽略NaN的一种方法是:

operator<

答案 1 :(得分:2)

您的比较运算符

bool operator<(const screenPoint& left, const screenPoint& right){
  return left.x<right.x||left.y<right.y;
}

不正确。如果x小于left.y,则需要使用if语句,如果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);
}
相关问题