Yechiel Labunskiy
Yechiel Labunskiy

Reputation: 427

C++ set comparator using member fields

I would like to declare a set<int> as a member of my class, and I want to give it a custom comparator which will use the class instance fields inside of it.

Something like this:

class MyClass {
  public:
    MyClass() : my_set(fn_pt) {}
    std::vector<int> blocks;
    bool comp(int lhs, int rhs) {
      return blocks[lhs] < blocks[rhs];
    }
    bool(*fn_pt)(int,int)=comp;
    std::set<int, bool(*)(int,int)> my_set;
};

This gives an error:

error: cannot convert ‘MyClass::comp’ from type ‘bool (MyClass::)(int, int)’ 
to type ‘bool (*)(int, int)’
bool(*fn_pt)(int,int)=comp;

How can I get it to work? Thanks

Upvotes: 0

Views: 654

Answers (1)

Jarod42
Jarod42

Reputation: 217418

As state in error MyClass::comp is bool (MyClass::)(int, int) not bool (*)(int, int).

As you actually use this, making the method static is not a solution, you may instead do

std::set<int, std::function<bool(int, int)>> my_set;

and then

MyClass() : my_set([this](int lhs, int rhs) { return blocks[lhs] < blocks[rhs]; }) {}

Upvotes: 3

Related Questions