Why does the C++ map type argument require an empty constructor when using []

Link to *: Why does the C++ map type argument require an empty constructor when using [] by Nick Bolton?

Q:

Not a major issue, just annoying as I don't want my class to ever be instantiated without the particular arguments.

#include <map>

struct MyClass
{
    MyClass(int t);
};

int main() {
    std::map<int, MyClass> myMap;
    myMap[14] = MyClass(42);
}

This gives me the following g++ error:

/usr/include/c++/4.3/bits/stl_map.h:419: error: no matching function for call to ‘MyClass()’

This compiles fine if I add a default constructor; I am certain it's not caused by incorrect syntax.

PS: This problem also causes an error:

C++ Compiler Error C2280 “attempting to reference a deleted function” 

in Visual Studio 2013 and 2015.

A:

This issue comes with operator[]. Quote from SGI documentation:

data_type& operator - Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object, operator[] inserts the default object data_type().

If you don't have default constructor you can use insert/find functions. Following example works fine:

myMap.insert( std::map< int, MyClass >::value_type ( 1, MyClass(1) ) );

myMap.find( 1 )->second;
上一篇:学习C#之旅 冒泡排序,选择排序,插入排序,希尔排序[资料收集]


下一篇:封装导出excel函数