我试图使用用户定义的类型作为具有自定义比较器的映射键,如下所示.
#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;
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是,如果两个RangeKey实例的范围重叠,则将它们视为相等.但是当我尝试在插入后检索一个值时,它会给我一些垃圾值作为主函数输出.我在这做错了什么?
| 归档时间: |
|
| 查看次数: |
1601 次 |
| 最近记录: |