c++ - 创建一个求和函数以仅对 vector 的一部分求和

标签 c++ stl vector

显然我需要一个求和函数,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/

相关文章:

c++ - macOS 上的 Qt GUI 应用程序 : how to find the currently active screen?

c++ - 这行得通吗? C++ 多重继承和构造函数链接

c++ - 指向结构错误 vector 的指针

matlab - 在 Matlab 中绘制 3D 向量

c++ - 如何在不使用循环或 std::accumulate() 的情况下计算 vector 的总和?

c++ - 非终止 while 循环

c++ - Dijkstra 算法 : memory consumption

c++ - 为什么这行得通? std::set 使用搜索键和自定义比较器查找

c++ - 破坏 std::stringbuf 导致访问冲突

c++ - 一组(异构) vector 的 Push_back 实现