![]() |
VOOZH | about |
The std::map::insert() is a built-in function of C++ STL map container which is used to insert new elements into the map. In this article, we will learn how to use map::insert() function in our C++ programs.
Example:
1: one 2: two 4: four
The map::insert() function provides 4 different overloads:
m.insert({k, v}) // For single element
m.insert(pos, {k, v}) // For single element near pos
m.insert({ {k1, v1}, {k2, v2}, ....}); // For multiple elements
m.insert(first, last); // For range
We can use these overloads for different ways to insert elements in std::map() in C++:
Table of Content
We can use the map::insert() to insert a key value pair in the map. It will be inserted at the position according to the order of the map elements.
m.insert({k, v})
Parameters
Return Value
Note: As map contains only unique key value pairs, map::insert() function won't insert the elements that is already present in the map.
The insert() function is essential for adding elements to a map.
1: one 2: two 4: four
Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: O(1)
We can also use the map::insert() function to insert the key-value pair near the given position. std::map has to maintain the order of elements. We cannot force the insertion at any particular position, so the given position only gives a hint to the map::insert() function as from where to start searching for the place to insert.
m.insert(pos, {k, v})
Parameters
Return Value
1: one 2: two 4: four
Time Complexity: O(log n)
Auxiliary Space: O(1)
We can insert multiple key value pairs in a map using map::insert() by enclosing the multiple key value pairs inside the braces {} and separate each of them using a comma. This form is called initializer list.
m.insert({ {k1, v1}, {k2, v2}, ....});
Parameters
Return Value
1: one 2: two 4: four
Time Complexity: O(k log n), where n is the number of elements already present in the map.
Auxiliary Space: O(k), where k is the number of elements to be inserted.
The map::insert() function can also be used to insert elements from the given range. This range can by any STL container or an array.
m.insert(first, last);
Parameters
Return Value
1: one 2: two 4: four
Time Complexity: O(k log n), where n is the number of elements in the map.
Auxiliary Space: O(k), where k is the number of elements in the range.