C++ 如何计算 std::vector<int> 中的值的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6743003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How calculate sum of values in std::vector<int>
提问by Jame
Possible Duplicate:
sum of elements in astd::vector
可能的重复:
a 中元素的总和std::vector
I have std::vector<int>
and I want to calculate the sum of all the values in that vector.
Is there any built in function or I need to write my custom code?
我有std::vector<int>
并且我想计算该向量中所有值的总和。是否有任何内置函数或我需要编写自定义代码?
回答by John Calsbeek
Use the STL algorithm std::accumulate
, in the numeric
header.
std::accumulate
在numeric
标头中使用 STL 算法。
#include <numeric>
// ...
std::vector<int> v;
// ...
int sum = std::accumulate(v.begin(), v.end(), 0);
回答by Petar Minchev
回答by thephpdev
You would need to make your own custom code.
您需要制作自己的自定义代码。
int sum = 0; for (int i = 0; i < myvector.size(); i++) sum += myvectory[i];
The answer is in the variable 'sum'.
答案在变量“sum”中。