Iterate over a MultiSet in C++

This tutorial will discuss multiple ways to iterate over a multiset in C++.

Loop Over a MultiSet Using Iteraters

To iterate over all the elements of a multiset, we can employ iterators. The begin() function of the multiset returns an iterator pointing to its first element, while the end() function gives an iterator pointing just past the last element of the multiset. Thus, we can use a for-loop to traverse between these two iterators, incrementing the iterator step-by-step and accessing the element it points to, as demonstrated below:

#include <iostream>
#include <set>

int main()
{
   std::multiset<int> numSet {11, 22, 33, 44, 33, 44, 33, 55, 66, 77, 88};

    // Iterate over all elements in MultiSet using iterators
    for(auto it = numSet.begin(); it != numSet.end(); it++)
    {
        std::cout<< *it << ", ";
    }
    std::cout<<std::endl;
}

Output:

11, 22, 33, 33, 33, 44, 44, 55, 66, 77, 88,

This will loop through all elements of the multiset and display them on the console.

Loop Over a MultiSet Using Range Based For-loop

We can use the range-based for loop, introduced in C++11, to seamlessly navigate through all the elements of the multiset. In this approach, we simply need to structure our for-statement as follows:

#include <iostream>
#include <set>

int main()
{
   std::multiset<int> numSet {11, 22, 33, 44, 33, 44, 33, 55, 66, 77, 88};

    // Iterate over all elements in MultiSet
    // using Raneg Based for-loop
    for(const auto& elem : numSet)
    {
        std::cout<< elem<< ", ";
    }
    std::cout<<std::endl;
}

Output:

11, 22, 33, 33, 33, 44, 44, 55, 66, 77, 88,

Here, for each iteration, the value ‘element’ gets initialized with the current item from the multiset. Inside the loop block, we can directly access each individual multiset element.



    In summary, we can traverse a multiset either by leveraging iterators or by utilizing the range-based for loop.

    Let’s see the complete example,

    #include <iostream>
    #include <set>
    
    int main()
    {
        std::multiset<int> numSet {11, 22, 33, 44, 33, 44, 33, 55, 66, 77, 88};
    
        // Iterate over all elements in MultiSet using iterators
        for(auto it = numSet.begin(); it != numSet.end(); it++)
        {
            std::cout<< *it << ", ";
        }
        std::cout<<std::endl;
    
        // Iterate over all elements in MultiSet
        // using Raneg Based for-loop
        for(const auto& elem : numSet)
        {
            std::cout<< elem<< ", ";
        }
        std::cout<<std::endl;
    
        return 0;
    }
    

    Output

    11, 22, 33, 33, 33, 44, 44, 55, 66, 77, 88, 
    11, 22, 33, 33, 33, 44, 44, 55, 66, 77, 88,
    

    Summary

    Today, we learned how to iterate over a multiset in C++.

    Scroll to Top