multimap::insert() method in C++ STL

Multimaps are associative containers available in the C++ Standard Library. They are similar to a map with an addition that multiple elements can have the same keys. The multimap::insert() is a method available in the STL which inserts multiple elements into the multimap, effectively increasing the size by the number of elements inserted.

Syntax:

map_name.insert( pair<data_type1, data_type2 >( key , value ) ); //insert one element

map_name.insert( iterator_pos, pair<data_type1, data_type2 >( key , value ) ); //insert at specified position

map_name.insert( iterator_begin, iterator_end ); //insert a range of values

Parameters: The multimap::insert() accepts the following parameters:

1. Insert single element:

  • pair: This specifies a pair of key and value that is to be inserted into the multimap.


Return value: Iterator pointing to the inserted element

2. Insert at specified position:

  • iterator_pos: Hint for the position where the element can be inserted.
    Note: This insertion does not force the new element to be inserted at that position. Elements in a multimap follow a specific ordering that’s key dependent.
  • pair: This specifies a pair of key and value that is to be inserted into the multimap.

Return value: Iterator pointing to the inserted element

3. Insert a range:

  • iterator_begin: Iterator to first element
  • iterator_end: Iterator to last element (Note: range is [ iterator_begin, iterator_end))

Return value: none

Example of multimap::insert() method

#include<iostream>
#include<map>


using namespace std;

void print(multimap<int,int> m)
{
    multimap<int,int>::iterator it;
    for(it = m.begin(); it != m.end(); ++it)
        cout<< it->first <<" : "<<it->second<<endl;
    cout<<endl;
}

int main()
{
    multimap<int,int> m;
    multimap<int,int>::iterator it;

    cout<<"Single element:\n";
    m.insert( pair<int,int> (1,5) ); //insert single element
    it = m.insert( pair<int,int> (2,10) );
    m.insert( pair<int,int> (3,15) );

    print(m);
    cout<<"Insert at hinted position: ";
    cout<<endl;

    m.insert( it, pair<int,int> (3,25) ); //insert at a hinted position
    print(m);
    cout<<endl;

    cout<<"Insert a range:\n";

    multimap<int, int> m2;
    m2.insert( pair<int,int> (4,20) );
    m2.insert( pair<int,int> (5,25) );
    m2.insert( pair<int,int> (6,30) );

    m.insert( m2.begin(), m2.end()); //insert a range
    print(m);
}

Output:

Single element:
1 : 5
2 : 10
3 : 15

Insert at hinted position:
1 : 5
2 : 10
3 : 25
3 : 15

Insert a range
1 : 5
2 : 10
3 : 25
3 : 15
4 : 20
5 : 25
6 : 30

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top