Question

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.

Was it helpful?

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++;
}

OTHER TIPS

You could iterate over the multiset like you would over any other container, and stop once you've seen n elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top