Shaobo Zi
Shaobo Zi

Reputation: 729

custom std::set comparator using function pointer

Is it possible that I can declare a set with function pointer as its comparator as a data member?

bool lex_compare (const int& lhs, const int & rhs){
       return true;
    };

// So I can define a std::set testSet using function pointer:
set<int, bool(*)(const int & lhs, const int & rhs)> testSet (&lex_compare);

My question is How should I declare and define testSet as a data member using a function pointer as comparator?

NOTE: I know that functor can be a solution in my situation:

struct lex_compare {
    bool operator() (const int& lhs, const int& rhs) const{
        return ture;
    }
};

set<int, lex_compare> testSet;

I ma interested if there is a way that function pointer can do.

Upvotes: 0

Views: 1018

Answers (2)

Vaughn Cato
Vaughn Cato

Reputation: 64308

It's basically the same if you are doing this inside a class:

struct MyClass {
    static bool lex_compare (const int& lhs, const int & rhs){
           return ...;
        };

    set<int, bool(*)(const int & lhs, const int & rhs)> testSet;

    MyClass()
    : testSet(&lex_compare)
    {
    }
};

Making your lex_compare function be static makes it be a regular function so that you can get a regular function pointer to it.

With C++11 or later, this can be simplified:

struct MyClass {
    static bool lex_compare(const int& lhs, const int & rhs){
           return ...;
        };

    set<int, decltype(&lex_compare)> testSet {lex_compare};
};

As noted by R Sahu, using plain ints as parameters is better, so this becomes:

struct MyClass {
    static bool lex_compare(int lhs, int rhs) { return ...; }
    set<int, decltype(&lex_compare)> testSet {lex_compare};
};

Upvotes: 3

R Sahu
R Sahu

Reputation: 206577

My question is How should I declare and define testSet as a data member using a function pointer as comparator?

You can declare it just like you have,

set<int, bool(*)(const int &, const int &)> testSet;

You can initialize it in the member initialization list of a constructor.

MyClass::MyClass() : testSet (&lex_compare) { ... }

Recommended

You can simplify lex_compare to:

bool lex_compare (int lhs, int rhs){ ... }

Upvotes: 4

Related Questions