Get first N elements in a C++ multiset

只愿长相守 提交于 2019-12-06 04:58:56

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!