2012-03-31 41 views
4

我正在尝试写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才能使其正常工作?谢谢。

回答

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); 
+0

是的,你是对的。我会考虑如何重写它... – milo 2012-03-31 19:41:10

+0

@milo:你正在寻找什么被称为*词典比较*。 – 2012-03-31 19:41:45

+0

我增加了一个词典对比的例子。希望你不介意(并且我没有犯错:) – 2012-03-31 19:46:52