2012-04-07 82 views
3

我遇到了錯誤與下面的代碼C++的std ::地圖比較方法

struct MapKey { 
    std::string x; 
    std::string y; 
} 

std::map<MapKey, int> m; 

if (m.find(key) != m.end()) { 
    ...... 
} 

我收到一個錯誤說,

no match for "operator<" in '__x < __y' 

我相信問題是,映射鍵需要有一個比較方法,我想知道如何爲Mapkey實現一個。例如,

struct MapKey { 
    bool operator<(const MapKey &key) const { 
     ... what shall I put here? ... 
    } 
    std::string x; 
    std::string y; 
} 

謝謝。

回答

9

MapKey的定義定義這個(作爲一個自由的功能,而不是一個成員函數),你就設置:

bool operator <(MapKey const& lhs, MapKey const& rhs) 
{ 
    return lhs.x < rhs.x || lhs.x == rhs.x && lhs.y < rhs.y; 
} 

確保定義操作員inline如果定義是在頭文件,否則可能會導致鏈接器錯誤。

+0

感謝您的回覆。爲什麼定義運算符<作爲一個自由函數,而不是MapKey的成員函數有什麼特別的理由?謝謝。 – 2607 2012-04-07 01:22:24

+0

@ 2607:在技術上可行,但通常會導致不具有成員函數(例如賦值運算符)成員函數的運算符被認爲是不好的做法。 – ildjarn 2012-04-07 01:23:42

2

任何引起strict weak ordering的函數(可以帶const參數)都可以。還記得你不需要運算符==,但是兩個鍵a和b被認爲是等價的,當且僅當!(a < b)& &!(b < a)。

+0

下面是關於什麼嚴格的弱排序意味着另一篇優秀的文章:[Order I Say!](http://cpp-next.com/archive/2010/02/order-i-say/) – ildjarn 2012-04-07 22:48:59