unordered_multimap insert() in C++ STL (original) (raw)

Last Updated : 29 Jul, 2021

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:

Return Value: This method returns an iterator pointing to the newly inserted element.
Time Complexity:

Below programs illustrate the unordered_multimap::insert function:
Program 1:

CPP `

#include #include

using namespace std; int main(void) { // Declare unordered_multimap unordered_multimap<char, int> cmap = { { 'B', 2 }, { 'C', 3 }, { 'D', 4 }, { 'E', 5 }, };

// insert a key-value pair using insert()
auto pos
    = cmap.insert(cmap.begin(),
                  pair<char, int>('A', 1));

// print the map with the newly inserted key-value pair
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 #include

using namespace std; int main() { // Declare unordered_multimap unordered_multimap<char, int> cmap = { { 'b', 2 }, { 'c', 3 }, { 'd', 4 }, { 'e', 5 }, };

unordered_multimap<char, int> dmap
    = { { 'A', 1 },
        { 'G', 6 } };

// Insert the map from begin to end
cmap.insert(dmap.begin(), dmap.end());

// Print the map
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 #include

using namespace std; int main() { // Declare unordered_multimap unordered_multimap<char, int> cmap = { { 'B', 2 }, { 'C', 3 }, { 'D', 4 }, { 'E', 5 }, };

// Insert a new list
cmap.insert({ { 'A', 1 },
              { 'F', 6 },
              { 'G', 7 } });

// Print the map
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