我正在尝试编写std::map密钥有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;
}
Run Code Online (Sandbox Code Playgroud)
它说我"没有找到".我哪里弄错了?我该怎么写Comparator才能让它正常工作?谢谢.
考虑到使用比较器,以下两个是true:
Key(1,2) < Key(2,1)
Key(2,1) < Key(1,2)
Run Code Online (Sandbox Code Playgroud)
您可以使用词典顺序:
return (k1.i1 != k2.i1) ? (k1.i1 < k2.i1)
: (k1.i2 < k2.i2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |