简体   繁体   English

STL映射自定义比较器

[英]STL map custom comparator

I am trying to use a user defined type as a map key with a custom comparator as follows. 我试图使用用户定义的类型作为带有自定义比较器的映射键,如下所示。

#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;
}

The idea is to consider two RangeKey instances as equal if their ranges overlap. 想法是如果两个RangeKey实例的范围重叠,则认为它们相等。 However when I try to retrieve a value after the insertion it gives me some garbage values as the main function output. 但是,当我尝试在插入后检索值时,它给了我一些垃圾值作为主函数输出。 What am I doing wrong here? 我在这里做错了什么?

The comparator for a map needs to be a "strict weak ordering," ie it cannot be that Comp(A,B) returns true and also Comp(B,A) returns true. map的比较器必须是“严格弱排序”,即不能是Comp(A,B)返回true并且Comp(B,A)也返回true。 Your comparator is a violation of this. 您的比较器违反了此规定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM