c++ - 是否有一个 STL 算法采用谓词来总结 C++ 中向量的元素
问题描述
我一直致力于理解 C++ 库中给出的所有 STL 算法,我们应该避免使用 for_each 和 for 循环来解决问题。在大多数情况下,我能够找到适用的 STL 算法,但我不记得在使用谓词时总结了集合或范围的任何算法,而且我在论坛上也找不到解决方案。我正在使用 C++ 20。
唯一的目标是使用 STL 算法将向量中的偶数与变量相加。
解决方案
我会用std::accumulate
.
例子:
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> v{1,2,3,4,5};
auto result = std::accumulate(v.begin(), v.end(), 0,
[](auto x, auto y) {
return y%2==0 ? x+y : x;
});
std::cout << result << '\n'; // prints 6
}
推荐阅读
- r - 如何选择名称可变的data.table列
- sql - 如果具有相同详细信息的记录很少,我如何选择第一个生效日期?
- regex - 未定义的方法“匹配?” 为真:TrueClass (NoMethodError)
- python - 如何以vec格式保存fasttext模型?
- javascript - Google App Script未以所需格式打印列表项
- angular - 如何使用角度在 ts 文件中发送表单数据?
- reactjs - 我可以在 Context API 中使用 React Context API 还是必须合并它们?
- flutter - 如何将 Flutter App 中的图像上传到我的服务器并解码来自服务器的 json 响应?
- git - 在一个项目中同步两个存储库 + Sourcetree
- python - 如何更有效地根据先前列 y 中的值计算列 y+1(蒙特卡洛模拟)