获取C ++ multiset中的前N个元素 [英] Get first N elements in a C++ multiset

查看:1138
本文介绍了获取C ++ multiset中的前N个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取多重集结构中的前N个元素,而不必始终获取第一个(.begin())元素,然后将其擦除?

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

推荐答案


我只想总结前N个元素,而不影响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 +11库添加。这里是一个旧的编译器的解决方案:

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

这篇关于获取C ++ multiset中的前N个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆