我遇到了錯誤與下面的代碼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;
}
謝謝。
感謝您的回覆。爲什麼定義運算符<作爲一個自由函數,而不是MapKey的成員函數有什麼特別的理由?謝謝。 – 2607 2012-04-07 01:22:24
@ 2607:在技術上可行,但通常會導致不具有成員函數(例如賦值運算符)成員函數的運算符被認爲是不好的做法。 – ildjarn 2012-04-07 01:23:42