C++ map和set中的結構體
哇,好久沒來寫部落格了。
今天是發現了一個新大陸。
是這樣的,我想隨機生成一些整數對(x,y),然後需要判斷一個數對在之前有沒生成過。直觀的做法是弄一個bool型的二維陣列,但是這樣太耗費空間了,容易造成浪費。於是我想把每個整數對放在一個結構體裡,然後將結構體作為map的key,將一個bool型作為map的value。這樣建立一個對映的關係,來判斷整數對是否出現過。
於是一開始我就這樣寫了:
struct numPair {
int x;
int y;
numPair() {}
numPair(int _x, int _y) :x(_x), y(_y) {}
};
可是當我想在map裡插入這樣
map<numPair, bool> visit;
visit.insert(std::pair<numPair, bool>(numPair(10, 20),true));
VS編譯器報了這樣的錯誤:
============================================================================
錯誤C2664
“void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(
std::initializer_list<std::pair<const _Kty,_Ty>>)”: 無法將引數 1 從“numPair”轉換為“std::pair<const _Kty,_Ty> &&”
============================================================================
這就是問題所在!map中的元素是按照key的大小進行排序的。所以需要在自定義結構題中加入比較大小函式。於是我進行了修改,過載了<運算子:
struct numPair { int x; int y; numPair() {} numPair(int _x, int _y) :x(_x), y(_y) {} bool operator<(const numPair& other) { return x < other.x || x == other.x && y < other.y; } };
結果依然報同樣的錯誤:
============================================================================
錯誤C2664“void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(
std::initializer_list<std::pair<const _Kty,_Ty>>)”: 無法將引數 1 從“numPair”轉換為“std::pair<const _Kty,_Ty> &&”
============================================================================
想了半天,最後在stackoverflow中找到了問題所在:<的過載函式需要加上const !!!!!
struct numPair {
int x;
int y;
numPair() {}
numPair(int _x, int _y) :x(_x), y(_y) {}
bool operator<(const numPair& other) const {
return x < other.x || x == other.x && y < other.y;
}
};
如果想在set中存放結構體,也是同樣的做法。