简体   繁体   中英

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.

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

您可以像遍历任何其他容器那样遍历多multiset ,并在看到n元素后停止。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM