STL映射自定义比较器

时间:2016-06-01 01:59:56

标签: c++ stl

我正在尝试将用户定义的类型用作具有自定义比较器的映射键,如下所示。

#include <map>
#include <iostream>

class RangeKey {
  public:
    int start;
    int end;

    RangeKey(int start, int end) : start(start), end(end) {

    }

    bool withinRange(int value, bool inclusive) const {
      if (inclusive) {
        return (value >= start && value <= end);
    } else {
      return (value > start && value < end);
    }
  }

  bool overlapsWith(const RangeKey& r) const {
    if (r.withinRange(start, true) ||
        r.withinRange(end, true) ||
        (start < r.start && end > r.end)) {
      return true;
    }
    return false;
  }

};

class RangeKeyComparator {
  public:
    bool operator()(const RangeKey& a, const RangeKey& b) const {
      if (a.overlapsWith(b)) {
        return true;
      } else {
        return a.start < b.start;
      }
    }
};

int main() {
  std::map<RangeKey, int, RangeKeyComparator> m;
  m.insert(std::pair<RangeKey, int>(RangeKey(1, 2), 1));
  auto it = m.find(RangeKey(1, 2));

  std::cout << it->first.start << "\n";
  std::cout << it->first.end << "\n";
  std::cout << it->second << "\n";

  return 0;
}

如果两个RangeKey实例的范围重叠,则认为它们是相等的。但是当我尝试在插入后检索一个值时,它会给我一些垃圾值作为主函数输出。我在这里做错了什么?

1 个答案:

答案 0 :(得分:6)

map的比较器需要是“严格的弱排序”,即它不能是Comp(A,B)返回true而Comp(B,A)也返回true。你的比较器违反了这一点。

相关问题