[英]Problem with std::map and std::pair
我有一個小程序,我想執行測試
#include <map>
#include <iostream>
using namespace std;
struct _pos{
float xi;
float xf;
bool operator<(_pos& other){
return this->xi < other.xi;
}
};
struct _val{
float f;
};
int main()
{
map<_pos,_val> m;
struct _pos k1 = {0,10};
struct _pos k2 = {10,15};
struct _val v1 = {5.5};
struct _val v2 = {12.3};
m.insert(std::pair<_pos,_val>(k1,v1));
m.insert(std::pair<_pos,_val>(k2,v2));
return 0;
}
問題是,當我嘗試編譯它時,我收到以下錯誤
$ g++ m2.cpp -o mtest
In file included from /usr/include/c++/4.4/bits/stl_tree.h:64,
from /usr/include/c++/4.4/map:60,
from m2.cpp:1:
/usr/include/c++/4.4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = _pos]’:
/usr/include/c++/4.4/bits/stl_tree.h:1170: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = _pos, _Val = std::pair<const _pos, _val>, _KeyOfValue = std::_Select1st<std::pair<const _pos, _val> >, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’
/usr/include/c++/4.4/bits/stl_map.h:500: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename _Alloc::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [with _Key = _pos, _Tp = _val, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’
m2.cpp:30: instantiated from here
/usr/include/c++/4.4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’
m2.cpp:9: note: candidates are: bool _pos::operator<(_pos&)
$
我認為在密鑰上聲明操作符<可以解決問題,但它仍然存在。
可能有什么不對?
提前致謝。
問題是這樣的:
bool operator<(_pos& other)
應該是這樣的:
bool operator<(const _pos& other) const {
// ^^^^ ^^^^^
沒有第一個const
,比較的右邊( b
a < b
)中a < b
不能是const
,因為沒有const
,函數可以修改它的參數。
沒有第二const
,比較的左手側( a
在a < b
不能const
,因為沒有const
功能可以修改this
。
在內部,地圖的關鍵字始終是const
。
應該注意,您應該更喜歡使用非成員函數。 也就是說,更好的是自由功能:
bool operator<(const _pos& lhs, const _pos& rhs)
{
return lhs.xi < rhs.xi;
}
與您的類在同一名稱空間中。 (對於我們的例子,就在它下面。)
順便說一句,在C ++中,不需要使用struct
為結構類型變量的聲明添加前綴。 這是完美的,首選:
_pos k1 = {0,10};
_pos k2 = {10,15};
_val v1 = {5.5};
_val v2 = {12.3};
(雖然你的類型名稱是以非正統的方式命名的。:P)
最后,您應該更喜歡make_pair
實用程序函數來進行配對:
m.insert(std::make_pair(k1,v1));
m.insert(std::make_pair(k2,v2));
它使您不必寫出對的類型,並且通常更容易閱讀。 (特別是當更長的類型名稱出現時。)
小於運算符的簽名需要是bool operator<(const _pos& other) const
,否則map不能在const函數中使用此運算符,因為此成員函數聲明為非const。
我認為你對operator <的定義是錯誤的 - 右邊(本例中的參數)應該標記為const,它應該是一個const成員函數,例如
bool operator<(const _pos& other) const{
return this->xi < other.xi;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.