显然我需要一个求和函数,accumulate 不会削减它
我需要创建程序 - 一个 vector - 用户可以指定 n 个元素 - 求和函数只能对正元素求和,即使用户也可以输入负元素...
在 computeSum 函数中我还需要为整个组添加一个“成功”
computeSum (dataVec, howMany, total, sucess);
并为输入的人创建一个参数 - 所有负数但想对它们求和但不能,因为没有正数
if (success) {
cout << "The sum is " << total << endl;
}
else {
cerr << "Oops, you cannot add these elements.";
}
这就是我得到的
#include <iostream>
#include <vector> // need this in order to use vectors in the program
using namespace std;
int main()
{
vector<double> dataVec;
double i, n, howMany, total;
cout << "How many numbers would you like to put into the vector?";
cin >> n;
dataVec.resize(n);
for(vector<double>::size_type i=0;i < n;i++)
{
cout << "Enter the numbers: \n";
cin >> dataVec[i];
}
cout << "How many POSITIVE numbers would you like to sum?";
cin >> howMany;
cout << computeSum (dataVec, howMany, total);
}
double computeSum (vector<double> &Vec, howMany, total)
{
double total =0;
for(int i=0;i < howMany;i++)
total+=Vec[i];
return total;
}
我似乎也无法编译这个 - computeSum() 在 int main() 中不被理解; howMany 在 computerSum() 中不被理解;并且在全局范围内 total() 和 howMany() 未声明(我想这意味着我需要在全局范围内贴花???)
最佳答案
事实上,accumulate
将“削减它”,使用一个只考虑正值的适当仿函数:
int sum_positive(int first, int second) {
return first + (second > 0 ? second : 0);
}
…
std::accumulate(data.begin(), data.begin() + how_many, 0, sum_positive);
关于c++ - 创建一个求和函数以仅对 vector 的一部分求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463310/