Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inserting object with constructor into map

I was trying to methods to insert into a map, inserting a pair into a map works fine, the code looks like this:

type insert(){
    map<int,MyClass> myMap;
    MyClass myObj(parameter);
    myMap.insert(pair<int,MyClass>(0,myObj));
    ...
    return myMap;
}

However, I decide to use the other way, basically:

    map[key] = value;

And, it look like this:

type insert(){
    map<int,MyClass> myMap;
    MyClass myObj(parameter);
    myMap[i] = myObj;
    ....
    return myMap;
 }

compiler will give an error saying: "no matching function for call to myObj::myObj(), candidates are: " and it gives my self defined constructor.

My guess is that when using the indexing way to cast to a map, if I were to pass in an object, then it will automatically call its default constructor with no parameter. But since I have already got a self defined constructor with parameter, it will therefore give an error. Therefore, I tried creating a map in which the value is an object, and the object has only default constructor. This way, compiler is not complaining.

My problem is I don't find any document confirming my idea. If it is right, why does the map with value of object made to call the default constructor rather than existing constructor?

like image 635
jer_yin Avatar asked Jan 15 '14 22:01

jer_yin


3 Answers

The problem is that std::map::operator[] will actually return a reference to the object on the given index and if there is non, default construct one. Your assignment takes place after acquiring a reference.

Use std::map::emplace to directly construct an object in place:

myMap.emplace(i, parameter);
like image 123
Sebastian Hoffmann Avatar answered Oct 25 '22 07:10

Sebastian Hoffmann


What happens when you call

myMap[i] = myObj;

is that, if there is no element with key i, one is inserted with a value initialized (which for a user defined type means default constructed) mapped type. You then assign to it the value on the RHS of the assignment. The first part requires that the type be default constructable.

like image 10
juanchopanza Avatar answered Oct 25 '22 07:10

juanchopanza


std::map requires your type must have a no-argument constructor. See here for a discussion of why.

like image 1
TypeIA Avatar answered Oct 25 '22 08:10

TypeIA