This question already has answers here:
Why does the C++ map type argument require an empty constructor when using []?
(5个答案)
6年前关闭。
我正在使用自己的类A作为map关键字的数据值来定义map。我也在使用 map 的find()函数。但是我得到了错误。
错误
不需要可用的默认构造函数。
(5个答案)
6年前关闭。
我正在使用自己的类A作为map关键字的数据值来定义map。我也在使用 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
最佳答案
问题是您使用的是operator[]来访问 map ,文档说:
因此,如果要使用它,则需要一个默认构造函数:该运算符需要它返回对新的默认构造并插入的元素的引用。
否则,您可以这样做:
m.insert(std::pair<int,A>(0,A(3)));
不需要可用的默认构造函数。
关于c++ - 在 map 上使用查找功能时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24763538/