unordered_map insert in C++ STL
Last Updated :
29 Oct, 2024
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:
C++
// C++ program to illustrate the use of
// unordered_map::insert()
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, string> um;
// Insert single elements in random order
um.insert({1, "one"});
// Insert multiple elements
um.insert({{2, "two"}, {4, "four"}});
for (auto i : um)
cout << i.first << ": " << i.second << '\n';
return 0;
}
Output4: four
2: two
1: one
unordered_map::insert() Syntax
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++:
Insert a Single Element
unordered_map::insert() method can be used to insert the single key value pair in std::unordered_map container.
Syntax
um.insert({k, v});
Parameters
- {k, v}: Key-value pair to be inserted.
Return Value
- Returns a pair, where pair::first is an iterator to either inserted element or the element with same key in the map.
- The pair::second tells whether the insertion was successful or not.
Example
C++
// C++ program to insert a single element using
// unordered_map::insert method
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, string> um;
// Insert single elements one by one
um.insert({1, "one"});
um.insert({4, "four"});
um.insert({2, "two"});
// Trying to insert duplicate key
um.insert({2, "TWO"});
for (auto i : um)
cout << i.first << '\t' << i.second << '\n';
return 0;
}
Time Complexity: O(1) average, O(n) worst, where n is the number of elements in unordered_map
Auxiliary Space: O(1)
Insert Element Near Given Position
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.
Syntax
um.insert(pos, {k, v});
Parameters
- {k, v}: Key-value pair to be inserted.
- pos: Iterator to the position near which the new element is to be inserted.
Return Value
- Returns an iterator pointing to either the inserted element or the element with same key in the map.
Example
C++
// C++ program to insert a pair near some given
// position using unordered_map::insert()
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, string> um;
um.insert({1, "one"});
um.insert({4, "four"});
// Finding the position to insert
auto it = um.find(4);
// Inserting {2, "two"} starting the search
// from position where 4 is present
um.insert(it, {2, "two"});
for (auto i : um)
cout << i.first << '\t' << i.second << '\n';
return 0;
}
Time Complexity: O(1) average, O(n) worst, where n is the number of elements in unordered_map
Auxiliary Space: O(1)
Insert Multiple Elements
We can also use the std::unordered_map::insert() method to insert multiple elements at once using initializer list.
Syntax
um.insert({ {k1, v1}, {k2, v2}, …});
Parameters
- {k1, v1}, {k2, v2}, …: First pair, second pair and so on inside { } braces.
Return Value
- This function does not return anything.
Example
C++
// C++ program to insert multiple key-value pairs
// using initializer list with unordered_map::insert()
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, string> um;
// Insert multiple key-value pairs using
// initializer list
um.insert({{1, "one"}, {2, "two"}, {4, "four"}});
// Display the elements of the unordered_map
for (auto i : um)
cout << i.first << '\t' << i.second << '\n';
return 0;
}
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.
Insert Elements from Given Range
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.
Syntax
um.insert(first, last);
Parameters
- first: Iterator to the first element of the range.
- last: Iterator to the element just after the last element of the range.
Return Value
- This function does not return anything.
Example
C++
// C++ program to insert multiple elements from
// given range using unordered_map::insert()
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, string> um;
// Vector of pairs to insert into unordered_map
vector<pair<int, string>> v = {{1, "one"},
{2, "two"}, {4, "four"}};
// Insert elements from the defined range
um.insert(v.begin(), v.end());
for (auto i : um)
cout << i.first << '\t' << i.second << '\n';
return 0;
}
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.
Similar Reads
Unordered Map in C++ STL In C++, unordered_map is an unordered associative container that stores data in the form of unique key-value pairs. But unlike map, unordered map stores its elements using hashing. This provides average constant-time complexity O(1) for search, insert, and delete operations but the elements are not
7 min read
Different Ways to Initialize an unordered_map in C++ Initialization is the process of assigning the initial values to the std::unordered_map elements. In this article, we will learn different methods to initialize the std::unordered_map in C++.Table of ContentUsing Initializer ListBy Inserting Elements One by OneFrom Another std::unordered_mapFrom Ano
3 min read
Commonly Used Methods
Other Member Methods
Traversing a Map and unordered_map in C++ STL The maps are described as mapped associative containers for elements where each element has a key and value assigned to it. Another form of map container seen in the C++ STL is the unordered map. It is the same as map containers just that they don't store the data in sorted order.We can traverse map
5 min read
How to use unordered_map efficiently in C++ Pre-requisite: unordered_set,  unordered_map C++ provides std::unordered_set and std::unordered_map to be used as a hash set and hash map respectively. They perform insertion/deletion/access in constant average time. However, the worst-case complexity is O(n2).The reason is that the unordered_map
6 min read
map vs unordered_map in C++ In C++, map and unordered_map are the containers that store can store data in the form of key-value pairs, but they differ significantly in terms of underlying implementation and performance characteristics.The below table lists the primary differences between map and unordered_map container:mapunor
2 min read
How to create an unordered_map of tuples in C++? Tuple - A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed. Unordered Map does not contain a hash function for a tuple. So if we want to hash a tuple the
2 min read
How to create an unordered_map of user defined class in C++? unordered_map is used to implement hash tables. It stores key value pairs. For every key, a hash function is computed and value is stored at that hash entry. Hash functions for standard data types (int, char, string, ..) are predefined. How to use our own data types for implementing hash tables?unor
3 min read