In this article we will discuss how to insert a key value pair in std::map.

Map internally store elements in a pair of key value i.e.

So, to add an element in map we can use one of its member function insert() i.e.

It accepts an object of key value pair and returns an pair of map iterator and bool.

In the returned pair i.e.

bool represents the result of insertion and iterator represents the position of newly added element in map.

If insertion in map is successful then,
bool —> true
Iterator —-> Points to Position of newly added element.

If insertion in map failed then,
bool —> false
Iterator —-> Pointing to the passed pair

Let’s see an example,

Suppose we have a map of string & int as key value pair i.e.

To insert an element in it we will create a pair of string & int i.e.

insert() function will return a pair of map iterator & bool i.e.

Now, to check if insertion we will first check the bool in result pair i.e.

Complete example is as follows,



To compile the above example in linux use following command,

g++ -std=c++11 example.cpp

Click Here to Subscribe for more Articles / Tutorials like this.