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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:36:36  来源:igfitidea点击:

How calculate sum of values in std::vector<int>

c++

提问by Jame

Possible Duplicate:
sum of elements in a std::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 numericheader.

std::accumulatenumeric标头中使用 STL 算法。

#include <numeric>

    // ...
    std::vector<int> v;
    // ...
    int sum = std::accumulate(v.begin(), v.end(), 0);

回答by Petar Minchev

accumulate(v.begin(), v.end(), 0);

accumulate(v.begin(), v.end(), 0);

Look herefor more details.

这里了解更多详情。

回答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”中。