Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map - adding element using subscript operator Vs insert method

Tags:

c++

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?

  1. mymap[10]='a';

  2. mymap.insert(mymap.end(), std::make_pair(10, 'a'));

  3. 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?

like image 605
voyager Avatar asked May 24 '19 08:05

voyager


2 Answers

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.

like image 146
lubgr Avatar answered Nov 15 '22 03:11

lubgr


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.

like image 25
L. F. Avatar answered Nov 15 '22 04:11

L. F.