試圖刷新我的C++和STL熟練程度,遇到由我定義的結構鍵入的std :: map問題。相關代碼:std :: map插入錯誤:沒有操作符「<」匹配這些操作數
typedef struct key_t {
int a;
int b;
bool operator==(const key_t& rhs)
{
return (a == rhs.a) && (b == rhs.b);
}
bool operator<(const key_t& rhs) //added the when I saw this error, didn't help
{
return a < rhs.a;
}
} key_t;
std::map<key_t, int> fooMap;
void func(void)
{
key_t key;
key.a = 1;
key.b = 2;
fooMap.insert(std::pair<key_t, int>(key, 100));
}
錯誤看起來是這樣的:
"/opt/[redacted]/include/functional", line 133: error: no operator "<" matches these operands
operand types are: const key_t < const key_t
detected during:
instantiation of "bool std::less<_Ty>::operator()(const _Ty &, const _Ty &) const [with _Ty=key_t]" at line 547 of "/opt/[redacted]/include/xtree"
instantiation of "std::_Tree<_Traits>::_Pairib std::_Tree<_Traits>::insert(const std::_Tree<_Traits>::value_type &) [with _Traits=std::_Tmap_traits<key_t, UI32, std::less<key_t>, std::allocator<std::pair<const key_t, UI32>>, false>]"
我在做什麼錯?它是不是很糟糕/不可能使用結構作爲地圖鍵?或者我忽略的其他東西?
+1對於格式正確的代碼,清楚地解釋了問題並顯示具體錯誤。 –
您的'operator <'和您的'operator =='不一致,因爲只有'operator =='測試'b'。這不是你的問題的原因,但除非你解決它,否則你正在尋求麻煩。可能你應該把'operator <'改成'return a
john