我是 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;
}
Run Code Online (Sandbox Code Playgroud)
要传递给的函数std::accumulate采用 2 个值:当前累积值和当前元素的值。
您应该做的是,如果它是偶数,则添加该值,如果不是,则不要更改。
int m = accumulate(vet.begin(), vet.end(), 0,
[](int cur, int m) {
if ((m % 2) == 0) {
return cur + m; // add this element
} else {
return cur; // make no change
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
490 次 |
| 最近记录: |