c++算法 - count_if对象中的第三个参数

标签 c++ algorithm parameters countif

<分区>

如果我试图在另一个类中传递一个函数,我很难理解如何使用 count_if 的第三个参数。当我在类外部创建 bool 函数时似乎没有任何问题,但是当我尝试将类内部的 bool 函数传递给 count_if 的第三个参数时,我收到“函数调用缺少参数列表”错误.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

//bool greater(int i); // this works

class testing {
    vector<int> vec;
public:
    testing(vector<int> v) {
        vec = v;
    }

    bool greater(int i) { // this doesn't work
        return i > 0;
    }

    void add(int i) {
        vec.push_back(i);
    }

    void display() {
        for (size_t j = 0; j < vec.size(); j++)
            cout << vec[j] << endl;
    }
};

int main() {
    vector<int> vec;
    testing t(vec);
    for (int i = 0; i < 5; i++) {
        t.add(i);
    }
    t.display();

    //cout << count_if(vec.begin(), vec.end(), greater); // this works
    cout << count_if(vec.begin(), vec.end(), t.greater); // this doesn't work

    system("pause");
    return 0;
}

/*bool greater(int i) { // this works
    return i > 0;
}*/

最佳答案

您可以将函数作为第三个参数传递给 count_if()。您不能做的是传递类方法。

greater() 是一个类方法。这意味着它不是一个独立的函数,而是类实例上的一个方法。

在这里做什么?只需将其设为静态类函数即可:

static bool greater(int i) { // this now works.
    return i > 0;
}

关于c++算法 - count_if对象中的第三个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35931630/

相关文章:

arrays - 如何从两个排序数组的交替元素生成所有可能的排序数组?

c++ - 我们应该修改函数签名以进行单元测试吗?

c++ - 水平/垂直均匀分布网格单元?

c++ - 为 vector 分配内存

带有数组和变量的 Javascript 任务

algorithm - 这个算法的时间复杂度是多少?

ruby-on-rails - 如何将一些参数传递给默认渲染方法?

XSLT 与 XProc - 所需类型中的参数绑定(bind)

REST 和 DELETE -> 传递参数

c++ - Visual C++ 2010 - 转换 10 GB BYTE 数组的最快方法?