Javatpoint Logo
Javatpoint Logo

C++ map insert() function

C++ map insert() function is used for inserting a new element in the map.

Because element keys are unique in a map, the insertion operation first checks whether the given key is already present in the map or not, if the key is present in the map then it is not inserted in the map and the iterator to the existing key is returned otherwise new element is inserted in the map.

Syntax

Parameter

val: key value to insert in the map.

position: Hint for the position to insert element.

first: Beginning of range to insert.

last: End of range to insert.

il: An initializer list.

Return value

It returns a bool pair to indicate whether insertion is happened or not and returns an iterator pointing to the newly inserted element.

Example 1

Let's see a simple example to insert the elements into the map.

Output:

Map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5

In the above example, it simply inserts the element with the given key value pair.

Example 2

Let's see a simple example to insert the element in the specified position:

Output:

Map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5

In the above example, elements are inserted in the defined position i.e. in begin element {'a', 1} is inserted and in the end element {'e', 5} is inserted.

Example 3

Let's see a simple example to insert the elements of one map to another.

Output:

Map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5

In the above example, map m1 has five elements and map m2 is empty. insert() function is used to insert the element of m1 to m2 from the beginning of m1 to end of m1 and displaying the content of m2 map.

Example 4

Let's see a simple example to insert the element.

Output:

Map contains following elements
1 : Java
2 : C++
3 : SQL
4 : VB
5 : Oracle

In the above example, another form of insert() function is used to insert the elements into the map.

Next TopicC++ Map



Help Others, Please Share

facebook twitter pinterest