Saturday 2 December 2017

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

itemprop="text">


See
also
href="https://stackoverflow.com/questions/695372/c-standard-list-and-default-constructible-types">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


struct MyClass
{
MyClass(int
t);
};


int main() {

std::map 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.



Answer




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;

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...