我正在尝试编写std::map
容器,其中key有2个值。这是一个例子:
#include <map>
#include <iostream>
using namespace std;
struct Key {
int i1;
int i2;
struct Comparator {
bool operator() (const Key& k1, const Key& k2) {
if (k1.i1 < k2.i1)
return true;
else if (k1.i2 < k2.i2)
return true;
return false;
}
};
};
int main() {
std::map<Key, int, Key::Comparator> tree;
for (int i = 0; i < 100; ++i) {
for (int j = 0; j < 10; ++j) {
Key key = {i, j};
tree[key] = i * j;
}
}
cout << "tree size: " << tree.size() << endl;
Key key = {45, 3};
std::map<Key, int, Key::Comparator>::iterator it = tree.find(key);
if (it == tree.end()) {
cout << "nothing has found" << endl;
return 1;
}
cout << "value: " << it->second << endl;
return 0;
}
它说我“没有找到”。我哪里弄错了?我该如何写Comparator
以使其正常工作?谢谢。
答案 0 :(得分:6)
考虑到使用比较器,以下两个都是true
:
Key(1,2) < Key(2,1)
Key(2,1) < Key(1,2)
您可以使用lexicographical order:
return (k1.i1 != k2.i1) ? (k1.i1 < k2.i1)
: (k1.i2 < k2.i2);