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?
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);
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.
std::map
requires your type must have a no-argument constructor. See here for a discussion of why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With