Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

dictionary

See also C++ standard list and default-constructible types

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.

like image 604
Nick Bolton Avatar asked Mar 29 '09 23:03

Nick Bolton


1 Answers

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; 
like image 86
bayda Avatar answered Sep 24 '22 06:09

bayda