3
我正在使用我自己的類A作爲地圖的關鍵字的數據值來定義地圖。我也使用map的find()函數。但我得到的錯誤。在地圖上使用查找功能的錯誤
#include<iostream>
#include<map>
using namespace std;
class A{
public:
int x;
A(int a){
x=a;
}
};
int main(){
map<int,A> m;
m[0]=A(3);
m[1]=A(5);
m[2]=A(6);
if(m.find(3) == m.end())
cout<<"none"<<endl;
else
cout<<"done"<<endl;
}
錯誤
In file included from /usr/include/c++/4.6/map:61:0,
from temp.cpp:2:
/usr/include/c++/4.6/bits/stl_map.h: In member function ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int, _Tp = A, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, A> >, std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = A, std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]’:
temp.cpp:14:5: instantiated from here
/usr/include/c++/4.6/bits/stl_map.h:453:11: error: no matching function for call to ‘A::A()’
/usr/include/c++/4.6/bits/stl_map.h:453:11: note: candidates are:
temp.cpp:7:3: note: A::A(int)
temp.cpp:7:3: note: candidate expects 1 argument, 0 provided
temp.cpp:4:7: note: A::A(const A&)
temp.cpp:4:7: note: candidate expects 1 argument, 0 provided
使用[圖::插入(http://www.cplusplus.com/reference/map/map/insert/)也是一種選擇,如果OP擁有約默認構造強烈的感情 –
@Jason我已經更新問題,謝謝你的方式 –
如果我想獲得價值,該怎麼辦。例如A a = m [0]? – user3747190