BЈо*_*вић 13 c++ stl language-lawyer
今天我创建了一个地图,其中值类型没有默认构造函数.我很惊讶我不能使用operator []将元素插入到这个地图中,但我不得不使用insert方法.
那么,对于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;
}
Run Code Online (Sandbox Code Playgroud)
我这样编译:
[vladimir@sandbox 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&)
Run Code Online (Sandbox Code Playgroud)
operator[]确实需要默认构造性,因为此方法的语义要求如果密钥尚不存在,则创建适当的条目.从而:
map<TKey, TValue> mymap;
TKey foo = …;
TValue& x = mymap[foo];
Run Code Online (Sandbox Code Playgroud)
TValue()如果foo地图中不存在,则会创建并存储新对象,并返回对它的引用.
这个网站是一个很好的STL参考:http://www.sgi.com/tech/stl/
基本上,它表示map take具有强制性的2类型参数,Key并且Data.Data需要的是Assignable,丹尼尔说.Key但是,声明需要是可以与类型一起使用的类型Compare,即Compare指定其参数是类型的函数对象Key.在这种情况下,默认Compare函数对象是std::less<T>,它使用the Strict Weak Ordering来比较类型的对象.因此,如果您不更改类型,即使用默认值,将与类型一起使用,因此将与类型一起使用,因此需要与之类似.Toperator<Comparestd::less<T>Keyoperator<KeyKeyoperator<
希望有所帮助!我知道这有点无偿,我不是故意屈尊俯就,但我只是想确保如何对此进行推理是绝对清楚的.