2012-03-31 93 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