Search code examples
c++priority-queuecomparator

how can I specify the comparator class of priority_queue at runtime


I wanted to create a "generic" priority_queue which is a member of class A, such that I do not need to specify the comparator functor class at compile time. I will choose the comparator funtor at runtime. How can I achieve this goal? Below is a simplified example of my use case.

I cannot use any C++11 features.

class A{
    private:
        priority_queue<T, vector<T>, ?> *pq;

    public: 
        A(string );
        ~A();
};

A::A(string s) {
    if(s == "1") 
        pq = new priority_queue<T, vector<T>, Mycomparator1>;
    else (s == "2") 
        pq = new priority_queue<T, vector<T>, Mycomparator2>;
}

A::~A(){
    delete pq;
}

struct Mycomparator1 {
    bool operator()(const T&a, const T&b){
        return a.x > b.x;
    } 
};

struct Mycomparator2 {
    bool operator()(const T&a, const T&b){
        return a.y > b.y
    } 
};

int main(){
    string s(argv[1]);
    A(s);
}

Solution

  • You can't decide the type of the comparator at runtime. But what you can do is make a comparator who's behavior depends upon runtime values. A simple example that works for your case would be the following:

    struct MyComparator3 {
        bool compare_x;
        bool operator()(const T& a, const T& b) const {
            if (compare_x)
                return a.x > b.x;
            else
                return a.y > b.y;
        }
    };
    

    Another much more versatile possiblity would be using something like std::function<bool(T,T)>, or (since you said you can't use C++11) boost::function.