我正在尝试编写一个 std::map
容器,其中键有两个值。以下是示例:
#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
才能使其正常工作?谢谢。
k1.i1 != (k2.i1 ? ...)
。 - Oliver Charlesworth