I am trying to understand and make sure if three different ways to insert elements into a std::map
are effectively the same.
std::map<int, char> mymap;
Just after declaring mymap
- will inserting an element with value a
for key 10
be same by these three methods?
mymap[10]='a';
mymap.insert(mymap.end(), std::make_pair(10, 'a'));
mymap.insert(std::make_pair(10, 'a'));
Especially, does it make any sense using mymap.end()
when there is no existing element in std::map
?
The main difference is that (1) first default-constructs a key
object in the map in order to be able to return a reference to this object. This enables you to assign something to it.
Keep that in mind if you are working with types that are stored in a map, but have no default constructor. Example:
struct A {
explicit A(int) {};
};
std::map<int, A> m;
m[10] = A(42); // Error! A has no default ctor
m.insert(std::make_pair(10, A(42))); // Ok
m.insert(m.end(), std::make_pair(10, A(42))); // Ok
The other notable difference is that (as @PeteBecker pointed out in the comments) (1) overwrites existing entries in the map, while (2) and (3) don't.
Yes, they are effectively the same. Just after declaring mymap
, all three methods turn mymap
into {10, 'a'}
.
It is OK to use mymap.end()
when there is no existing element in std::map
. In this case, begin() == end()
, which is the universal way of denoting an empty container.
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