【发布时间】:2016-06-01 10:05:48
【问题描述】:
我正在尝试使用用户定义的类型作为带有自定义比较器的映射键,如下所示。
#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 实例的范围重叠,则认为它们是相等的。但是,当我尝试在插入后检索一个值时,它会给我一些垃圾值作为主函数输出。我在这里做错了什么?
【问题讨论】:
-
地图比较器不测试是否相等。地图比较器实现strict weak ordering。简单来说:
<运算符,而不是==运算符。