unordered_multimap insert() in C++ STL
The function std::unordered_multimap::insert() is a built-in function in C++ STL that extends container by inserting new element in unordered_multimap. This function increases container size by one. The insert() function can be used to insert a single key-value pair, a complete unordered_map, initialized list insertion etc.
Syntax:
iterator insert(const_iterator position, const value_type& val);
Parameters: This method takes following parameters:
- Position: position to insert element
- Value: value to be inserted
Return Value: This method returns an iterator pointing to the newly inserted element.
Time Complexity:
- O(1) in average case
- O(n) in worst case
Below programs illustrate the unordered_multimap::insert function:
Program 1:
CPP
#include <iostream>
#include <unordered_map>
using namespace std;
int main( void )
{
unordered_multimap< char , int > cmap = {
{ 'B' , 2 },
{ 'C' , 3 },
{ 'D' , 4 },
{ 'E' , 5 },
};
auto pos
= cmap.insert(cmap.begin(),
pair< char , int >( 'A' , 1));
for ( auto x : cmap)
cout << x.first << ": "
<< x.second << endl;
return 0;
}
|
Output:
A: 1
B: 2
C: 3
D: 4
E: 5
Program 2:
CPP
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_multimap< char , int > cmap = {
{ 'b' , 2 },
{ 'c' , 3 },
{ 'd' , 4 },
{ 'e' , 5 },
};
unordered_multimap< char , int > dmap
= { { 'A' , 1 },
{ 'G' , 6 } };
cmap.insert(dmap.begin(), dmap.end());
for ( auto x : cmap)
cout << x.first << ": "
<< x.second << endl;
return 0;
}
|
Output:
G: 6
A: 1
b: 2
c: 3
d: 4
e: 5
Program 3:
CPP
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_multimap< char , int > cmap = {
{ 'B' , 2 },
{ 'C' , 3 },
{ 'D' , 4 },
{ 'E' , 5 },
};
cmap.insert({ { 'A' , 1 },
{ 'F' , 6 },
{ 'G' , 7 } });
for ( auto x : cmap)
cout << x.first << ": "
<< x.second << endl;
return 0;
}
|
Output:
G: 7
F: 6
A: 1
B: 2
C: 3
D: 4
E: 5
Last Updated :
29 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...