【发布时间】:2020-10-08 14:36:01
【问题描述】:
我是 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 = accumulate(vet.begin(), vet.end(), 0,
[](int m) { for (auto m : vet) {
return (m % 2) == 0; });
cout << m << endl; //would love to see the sum of even values here
return 0;
}
【问题讨论】:
-
最后一个要累积的参数没有按照您的预期进行。请在问题中包含编译器错误消息
-
您应该阅读
std::accumulate的op参数的作用。