简体   繁体   English

使用std :: accumulate计算向量的一部分的总和

[英]Compute the sum of part of the vector using std:: accumulate

Having this vector 有这个向量

vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

how can I compute the sum of the first half of it (which is 15) using the accumulate function? 如何使用累加函数计算其前半部分(即15)的总和

Can I do this using the for loop with only the iterators (not numerical indexes)? 我可以使用只有迭代器(而不是数字索引)的for循环吗?

You can 您可以

accumulate(v.begin(), v.begin()+int(v.size()/2), 0)

if v is your vector. 如果v是你的向量。

You can also write a loop: 你也可以写一个循环:

int sum = 0;
for (vector<int>::iterator it = v.begin(); it != v.begin+int(v.size()/2); ++it) {
    sum += *it;
}

To work with just the first half you have to get iterators that cover just that range. 要仅使用上半部分,您必须获得仅涵盖该范围的迭代器。 Usually people want to work with an entire container and so they use begin and end functions, but that's not the only way: 通常人们想要使用整个容器,因此他们使用开始和结束函数,但这不是唯一的方法:

auto begin = std::begin(v);
auto middle = std::begin(v) + v.size()/2; // works for random access iterators

auto middle = begin;
std::advance(middle, v.size()/2);

advance works for input iterators or better, but for input iterators which are not also one of the other types the items that are advanced passed won't be accessible anymore. advance适用于输入迭代器或更好,但对于输入迭代器,它们也不是其他类型之一,高级传递的项目将不再可访问。

auto middle = std::next(begin, v.size()/2); // C++11. works for forward iterators

And these are only a few of the available operations you can perform on the different types of iterators. 这些只是您可以对不同类型的迭代器执行的一些可用操作。


So now that you can create iterators that specify your desired range you can use them either in std::accumulate or a manual for loop: 现在您可以创建指定所需范围的迭代器,您可以在std :: accumulate或手动循环中使用它们:

std::accumulate(std::begin(v), std::next(std::begin(v), v.size()/2), 0);

for (auto begin(std::begin(v)), end(begin+v.size()/2); begin!=end; ++begin) {
    ...
}
accumulate<int>(v.cbegin(), v.cbegin() + v.size()/2, 0);

int sum = std :: accumulate(v.begin(),v.begin()+ v.size()/ 2,0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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