2015-04-05 61 views
0

我寫了一個自己的比較器的地圖,並測試查找功能。但它似乎不起作用。代碼如下所示,我想創建一個映射,其鍵類型是一對,值類型是一個int。當我運行代碼時,它總是輸出「not find」而不是地圖中的某些值。有誰能告訴我爲什麼?地圖與自定義比較器不工作

#include <iostream> 
#include <map> 
using namespace std; 

struct Mycomp { 
    bool operator() (const pair<int, int> &a, const pair<int, int> &b) { 
     int firsta = a.first; 
     int seconda = a.second; 
     if(firsta > seconda) { 
      int temp = firsta; 
      firsta = seconda; 
      seconda = temp; 
     } 
     int firstb = b.first; 
     int secondb = b.second; 
     if(firstb > secondb) { 
      int temp = firstb; 
      firstb = secondb; 
      secondb = temp; 
     } 
     if(firsta != firstb) 
      return firsta <= firstb; 
     else 
      return seconda <= secondb; 
    } 
}; 

int main(void) { 
    map<pair<int, int>, int, Mycomp> mymap; 
    mymap.insert(std::make_pair(std::make_pair(0, 1), 10)); 
    mymap.insert(std::make_pair(std::make_pair(2, 3), 10)); 
    auto it = mymap.find(std::make_pair(1, 0)); 
    if(it == mymap.end()) 
     out << "not find" << endl; 
    else 
     cout << it->second << endl; 
    return 0; 
} 
+1

你比較不嚴格弱序。基本上,比較器應該模擬'<',而不是'<='。 – 2015-04-05 02:52:03

+0

謝謝,你的評論幫助我很多。 – 2015-04-05 04:09:00

回答

0

將評論由@IgorTandetnik轉換爲答案。

更換線路:

if(firsta != firstb) 
    return firsta <= firstb; 
else 
    return seconda <= secondb; 

通過

if(firsta != firstb) 
    return firsta < firstb; // Use < not <= 
else 
    return seconda < secondb;