今天我創建了一個映射,其中值類型沒有默認構造函數。我很驚訝我不能使用operator []將元素插入到這個映射中,但我不得不使用insert方法。std :: map的類型要求
那麼,對於std :: map的鍵和值類型的要求究竟是什麼?
下面是簡單的例子:
#include <map>
struct A
{
A(int){}
};
int main()
{
std::map< int, A > m;
A a1(2);
A a2(3);
A a3(4);
m[5] = a1;
m[3] = a2;
m[2] = a3;
}
我編譯如下:
[[email protected] tmp]$ g++ b5.cpp -Wall -Wextra -ansi -pedantic
/usr/lib/gcc/i386-redhat-linux/4.3.0/../../../../include/c++/4.3.0/bits/stl_map.h: In member function ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = A, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, A> >]’:
b5.cpp:14: instantiated from here
/usr/lib/gcc/i386-redhat-linux/4.3.0/../../../../include/c++/4.3.0/bits/stl_map.h:419: error: no matching function for call to ‘A::A()’
b5.cpp:5: note: candidates are: A::A(int)
b5.cpp:4: note: A::A(const A&)
原則上這是一個很好的答案,但它不能解釋爲什麼OP的代碼失敗。 – 2010-11-23 10:28:16