1

I have trouble understanding how to use the 3rd parameter of count_if if I am trying to pass a function inside of another class. It does not appear to have any issues when I create the bool function outside of a class but I am receiving a "function call missing argument list" error when I try to pass bool function which is inside of a class to the 3rd parameter of 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;
}*/

1 Answers1

0

You can pass a function as the third parameter to count_if(). What you can't do is pass a class method.

greater() is a class method. This means that it's not a standalone function, it's a method on an instance of a class.

What to do here? Simply make it a static class function:

static bool greater(int i) { // this now works.
    return i > 0;
}
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148