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

Multisets are associative containers available in the C++ Standard Library. They are similar to sets with an addition that multiple keys with equivalent values are allowed. The multiset::insert() is a method available in the STL that extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted.

Syntax:

set_name.insert( val ); //insert one element

set_name.insert( iterator_pos, val ); //insert at specified position

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

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

1. Insert single element:

  • val: This specifies the value that is to be inserted into the multiset.


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 multiset follow a specific ordering that’s key-dependent.
  • val: This specifies the value that is to be inserted into the multiset.

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 multiset::insert() method

#include <iostream>
#include <set>

using namespace std;

int main()
{
   multiset<int> m;
   m.insert(1);
   m.insert(2);
   
   multiset<int> m2;
   m2.insert(3);
   m2.insert(4);
   
   m.insert(m2.begin(), m2.end());
   
   multiset<int>::iterator it = m.begin();
   it++;
   
   m.insert(it, 1);
   
   for( auto i : m)
    cout<<i<<"  ";
}

Output:

1  1  2  3  4  

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