How to sum up elements of a C++ vector?(如何总结 C++ 向量的元素?)
问题描述
求 std::vector
中所有元素总和的好方法是什么?
What are the good ways of finding the sum of all the elements in a std::vector
?
假设我有一个向量 std::vector
,其中包含一些元素.现在我想找到所有元素的总和.相同的方法有哪些不同?
Suppose I have a vector std::vector<int> vector
with a few elements in it. Now I want to find the sum of all the elements. What are the different ways for the same?
推荐答案
其实方法很多.
int sum_of_elems = 0;
C++03
经典 for 循环:
Classic for loop:
for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
sum_of_elems += *it;
使用标准算法:
Using a standard algorithm:
#include <numeric>
sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);
重要提示:最后一个参数的类型不仅用于初始值,还用于结果的类型.如果你在那里放一个 int,即使向量有浮点数,它也会累积整数.如果要对浮点数求和,请将 0
更改为 0.0
或 0.0f
(感谢 nneonneo).另请参阅下面的 C++11 解决方案.
Important Note: The last argument's type is used not just for the initial value, but for the type of the result as well. If you put an int there, it will accumulate ints even if the vector has float. If you are summing floating-point numbers, change 0
to 0.0
or 0.0f
(thanks to nneonneo). See also the C++11 solution below.
C++11 及更高版本
b.即使在未来发生变化的情况下,也会自动跟踪向量类型:
b. Automatically keeping track of the vector type even in case of future changes:
#include <numeric>
sum_of_elems = std::accumulate(vector.begin(), vector.end(),
decltype(vector)::value_type(0));
使用 std::for_each
:
std::for_each(vector.begin(), vector.end(), [&] (int n) {
sum_of_elems += n;
});
使用基于范围的 for 循环(感谢 Roger Pate):
for (auto& n : vector)
sum_of_elems += n;
这篇关于如何总结 C++ 向量的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何总结 C++ 向量的元素?


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01