VOOZH about

URL: https://www.geeksforgeeks.org/cpp/multiset-in-cpp-stl/

⇱ Multiset in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Multiset in C++ STL

Last Updated : 1 Jun, 2026

Multiset is an associative container similar to a set, but it can store multiple elements with the same value. It is sorted in increasing order by default, but it can be changed to any desired order using a custom comparator.

  • Allows duplicate elements, unlike a set.
  • Supports standard set operations like insert(), erase(), count(), and find().
  • It uses a self-balancing Binary Search Tree, ensuring O(log n) time complexity for operations.

Output
1 3 3 5 

Explanation

  • ms1 creates an empty multiset of integers.
  • ms2 is initialized with four elements, including the duplicate value 3.
  • The multiset automatically stores elements in sorted order.
  • Unlike set, both occurrences of 3 are preserved and displayed.

Syntax

multiset<T> ms;

Where:

  • T -> data type of elements
  • ms -> name of the multiset

Basic Operations on Multiset

A multiset provides several built-in member functions to efficiently store, access, search, and remove elements while maintaining sorted order.

Inserting Elements

We can insert elements into a multiset by using insert() method. The multiset will automatically keep the elements sorted.


Output
1 3 3 5 

Accessing Elements

Elements cannot be accessed by index; use an iterator from begin() and advance it. The first element is *begin(), and the last is one step back from end().


Output
1 3

Finding Elements

Multiset provides fast search by value operation using the find() member function. This function returns iterator the element if found, otherwise returns end() iterator.


Output
3

Traversing

Use a range-based for loop or begin()/end() iterators to traverse a multiset. And It use equal_range() to traverse all elements with the same value.


Output
1 3 3 5 

Deleting Elements

The erase() method removes elements by value (all occurrences) or by iterator (specific element).


Output
5 

Note: Elements in a multiset cannot be updated or modified once inserted.

Comment