In C++, multiset is an associative container similar to the set, but it can store multiple elements with same value. It is sorted in increasing order by default, but it can be changed to any desired order. It provides fast insertion, deletion and search operations.
Example:
C++
#include <iostream>
#include <set>
using namespace std;
int main() {
// Creating a set of integers
multiset<int> ms = {5, 1, 3, 3};
for (auto i : ms)
cout << i << " ";
return 0;
}
Example: In this program, we created a multiset of integers ms and inserted four elements {5, 1, 3, 3} into it. The multiset allows duplicate elements, so the value 3 can appears twice.
Syntax
Multiset is defined as std::multiset class template inside <set> header file.
multiset<T, comp> ms;
where,
- T: Datatype of elements in the multiset.
- ms: Name assigned to the multiset.
- comp: It is a binary predicate function that tells multiset how to compare two elements in sorting. It is optional and if not provided, multiset is sorted in increasing order.
Declaration and Initialization
We can declare and initialize a multiset in multiple ways as shown in the below example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// Creating an empty set of integers
multiset<int> ms1;
// Initialize with initializer list
multiset<int> ms2 = {5, 3, 3, 1};
for (auto i : ms2)
cout << i << " ";
return 0;
}
Explanation: In the above program,
- Statement multiset<int> ms1 creates an empty multiset of integers.
- Statement multiset<int> ms2 = {5, 3, 3, 1} initializes the multiset with values from an initializer list.
Basic Operations
Here are the basic operations that can be performed on a multiset:
1. Inserting Elements
We can insert elements into a multiset by using insert() method. The multiset will automatically keep the elements sorted.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
multiset<int> ms;
// Inserting elements
ms.insert(5);
ms.insert(3);
ms.insert(3);
ms.insert(1);
for(auto i : ms)
cout << i << " ";
return 0;
}
To know more methods of insertion, refer to the article - Different Ways to Insert Elements into Multiset
2. Accessing Elements
In multiset, we have to use iterator to access the elements by their position. For example, to access 3rd element, we have to move the begin() iterator two positions by incrementing. We can also use next() or advance() function instead of incrementing or decrementing.
However, we can quickly access the first and last element using begin() and end() iterators.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
multiset<int> ms = {5, 3, 3, 1};
// Access first element
auto it1 = ms.begin();
cout << *it1 << " ";
// Access third element
auto it2 = next(it1, 2);
cout << *it2;
return 0;
}
Explanation: In the above program, s.begin() returns an iterator to the first element of the multiset which is stored in it1. To access the third element, next() is used to move the iterator it1 by 2 positions and store it in it2. The *it1 and *it2 dereference the iterators to access the values at those positions.
3. Updating Elements
We cannot change the value of elements once they are stored in the set.
4. 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.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
multiset<int> ms = {5, 3, 3, 1};
// Finding 3
auto it = ms.find(3);
if (it != ms.end()) cout << *it;
else cout << "Not Found!";
return 0;
}
5. Traversing
Just like other containers, multisets can be easily traversed using range-based for loop or using begin() and end() iterators. To traverse all the elements with same key, se the range returned by equal_range() function instead of begin() and end().
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
multiset<int> ms = {5, 3, 3, 1};
// Traversing using range-based loop
for(auto i : ms)
cout << i << " ";
return 0;
}
6. Deleting Elements
To delete elements from a multiset, use the erase() method. This method can be used either by passing the value or an iterator. But if the value is passed, it deletes all the occurrences of that value.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
multiset<int> ms = {5, 3, 3, 1};
// Delete first element
ms.erase(ms.begin());
// Deleting all 3s
ms.erase(3);
for (auto x: ms) cout << x << " ";
return 0;
}
To know more methods of deletion, refer to the article - Different Ways to Remove Elements from Multiset
Other Common Operations
The following examples aim to help you master multiset operations beyond the basic operations:
Internal Working
In C++, multiset is an associated container that provides the built-in implementation of Red-Black Tree. Similar to set, it allows for fast insertion, deletion, and searching of elements in logarithmic time, O(log (n)). But it also allows duplicate elements i.e. multiple copies of the same element are stored in the tree structure. The same values are sorted on the basis of their insertion order.
Multiset vs Set
Following is the primary differences between set and unordered_set in C++:
- Set stores unique elements in sorted order.
- Multiset allows duplicate elements to be stored in sorted order.
All Member Functions
Following is the list of all member functions of std::multiset class in C++:
Function | Definition |
---|
begin() | Returns an iterator to the first element in the multiset. |
end() | Returns an iterator pointing to the beyond of the last element of the multiset. |
size() | Returns the number of elements in the multiset. |
max_size() | Returns the maximum number of elements that the multiset can hold. |
empty() | Returns whether the multiset is empty. |
insert() | Adds a new element 'g' to the multiset. |
erase() | Removes the element at the position pointed by the iterator. |
clear() | Removes all the elements from the multiset. |
find() | Returns an iterator to the element 'g' in the multiset if found, else returns the iterator to end. |
count() | Returns the occurrence of an element in multiset. |
lower_bound() | ind the first element in the multiset that is equal to or greater than the given value |
upper_bound() | Find the first element in the multiset that is just greater than the given value. |
swap() | This function is used to exchange the contents of two multisets but multisets must be of the same type, although sizes may differ. |
emplace() | This function is used to insert a new element into the multiset container. |
equal_range() | Returns an iterator of pairs. The pair refers to the range that includes all the elements in the container which have a key equivalent to k. |
rbegin() | Returns a reverse iterator pointing to the last element in the multiset container. |
rend() | Returns a reverse iterator pointing to the theoretical element right before the first element in the multiset container. |
cbegin() | Returns a constant iterator pointing to the first element in the container. |
cend() | Returns a constant iterator pointing to the position past the last element in the container. |
crbegin() | Returns a constant reverse iterator pointing to the last element in the container. |
crend() | Returns a constant reverse iterator pointing to the position just before the first element in the container. |
get_allocator() | Returns a copy of the allocator object associated with the multiset. |
Similar Reads
Multiset in C++ STL In C++, multiset is an associative container similar to the set, but it can store multiple elements with same value. It is sorted in increasing order by default, but it can be changed to any desired order. It provides fast insertion, deletion and search operations.Example:C++#include <iostream
6 min read
Commonly Used Methods
Other Member Functions
Multiset of Pairs in C++ with Examples What is Multiset? A multiset is an associative container that can hold a number of elements in a specific order. Unlike a set, a multiset can contain multiple occurrences of the same element. Some of the functions associated with a multiset: begin(): Returns an iterator to the first element in the m
4 min read
Multiset of Vectors in C++ with Examples What is Multiset? A multiset in C++ is an associative container that can hold a number of elements in a specific order. Unlike a set, a multiset can hold multiple copies of the same element. Functions associated with a multiset: begin(): Returns an iterator to the first element in the multiset.end()
4 min read
Multiset of Tuples in C++ with Examples What is a tuple? A tuple in C++ is an object which binds a group of elements together. The elements can be similar as well as different data types. The elements of tuples are initialized as in the order in which they will be accessed. Syntax: tuple<data_type1, data_type2, dataType3, ....> myTu
5 min read
Multi-set for user defined data type You are given Q queries. Each query contains an integer k and a person's information i.e, first name, last name, age. For each query, we need to output Kth person among them if all person information are arrange in ascending order. Note: Person A comes before person B if first name of A is lexicogra
3 min read