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

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

data_type& operator[](const key_type& k) – 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;

Leave a Comment