唯一可用的选项是std::ranges::for_each简单的基于范围的for循环。没有对应的std::accumulate,std::reduce或std::inner_product。std::ranges::reduce如果有的话就足够了;内积可以结合reduce和zip来实现。回到基于迭代器的算法是令人失望的。为个人代码库调整reduce并不是什么大问题,但恕我直言,std函数更可取。我想知道 std lib 或 23 地平线上是否有这样的功能。
问候,FM。
我是 C++ 的新手,我完全不了解如何只对存储在 C++ 中的向量中的偶数值求和。
任务本身要求用户输入一定数量的随机整数,当输入为 0 时停止,然后返回偶数值的数量和这些偶数值的总和。
这是我设法得到的:
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
vector<int> vet;
int s = 1;
while (s != 0) {
std::cin >> s;
vet.push_back(s);
}
int n = count_if(vet.begin(), vet.end(),
[](int n) { return (n % 2) == 0; });
cout << n << endl;
//here is the start of my problems and lack of undertanding. Basically bad improv from previous method
int m …Run Code Online (Sandbox Code Playgroud)