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

c++ algorithm - count_if 3rd parameter in an object

如果我试图在另一个 class 中传递一个函数,我很难理解如何使用 count_if 的第三个参数。当我在 class 之外创建 bool 函数时似乎没有任何问题,但是当我尝试传递 class 内部的 bool 函数时收到 "function call missing argument list" 错误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()。您不能做的是传递 class 方法。

greater() 是一种 class 方法。这意味着它不是一个独立的函数,它是 class.

实例上的一个方法

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

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