Search code examples
c++multiset

Get first N elements in a C++ multiset


How can I get the first N elements from a multiset structure, without constantly getting the first (.begin()) element and then erasing it?

I just want to sum the first N elements without affecting the multiset.


Solution

  • I just want to sum the first N elements without affecting the multiset.

    #include <numeric>
    #include <iterator>
    
    // ...
    
    int sum = std::accumulate(my_set.begin(), std::next(my_set.begin(), N));
    

    std::next is a C++11 library addition. Here is a solution for older compilers:

    std::multiset<int>::iterator it = my_set.begin();
    std::advance(it, N);
    int sum = std::accumulate(my_set.begin(), it);
    

    Both solutions iterate over the multiset twice. If you want to prevent that, use a manual loop:

    int sum = 0;
    std::multiset<int>::iterator it = my_set.begin();
    for (int i = 0; i < N; ++i)
    {
        sum += *it++;
    }