![]() |
VOOZH | about |
The std::unordered_map::insert() in C++ STL is a built-in function used to insert a key-value pair in unordered_map container. As unordered maps only store unique elements, this function does not insert elements with duplicate keys. In this article, we will learn about std::unordered_map::insert() in C++.
Example:
4: four 2: two 1: one
um.insert({k, v}) // For single element
um.insert(pos, {k, v}) // For single element near pos
um.insert({ {k1, v1}, {k2, v2}, ….}); // For multiple elements
um.insert(first, last); // For range
We can use these overloads for different ways to insert elements in std::map() in C++:
Table of Content
unordered_map::insert() method can be used to insert the single key value pair in std::unordered_map container.
um.insert({k, v});
Parameters
Return Value
2 two 4 four 1 one
Time Complexity: O(1) average, O(n) worst, where n is the number of elements in unordered_map
Auxiliary Space: O(1)
We can also use the unordered_map::insert() function to insert the key-value pair near the given position. The std::unordered_map are stored according to their hash codes. We cannot force the insertion at any particular position, so the given position only gives a hint to unordered_map::insert() function.
um.insert(pos, {k, v});
Parameters
Return Value
2 two 4 four 1 one
Time Complexity: O(1) average, O(n) worst, where n is the number of elements in unordered_map
Auxiliary Space: O(1)
We can also use the std::unordered_map::insert() method to insert multiple elements at once using initializer list.
um.insert({ {k1, v1}, {k2, v2}, …});
Parameters
Return Value
4 four 2 two 1 one
Time Complexity: O(k) average, O(n * k) worst, where n is the number of elements in unordered_map.
Auxiliary Space: O(k), where k is the number of elements to be inserted.
The unordered_map::insert() function can also be used to insert elements from the given range. This range can by any STL container or an array.
um.insert(first, last);
Parameters
Return Value
4 four 2 two 1 one
Time Complexity: O(k) average, O(n * k) worst, where n is the number of elements in unordered_map.
Auxiliary Space: O(k), where k is the number of elements to be inserted.