![]() |
VOOZH | about |
In C++, a multiset is a container similar to a set but it allows multiple occurrences of its elements i.e. duplicate values. In this article, we will learn how to find all occurrences of a specific element in a multiset in C++.
Example:
Input:
myMultiset = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
target = 3
Output:
The element 3 occurred at position: 3 4 5
To find all occurrences of an element in a std::multiset in C++, we can use the std::set::equal_range() function that returns the pair that contains the iterator to the range of set elements containing our target elements. We can then use the std::distance() function to get the position of these elements.
The below example demonstrates how we can find all occurrences of an element in a multiset in C++.
The element 3 occurred at indices: 3 4 5
Time Complexity: O(K + logN), here N is the number of elements in the multiset and K is the number of occurences.
Auxilliary Space: O(1)