如何在运行时指定 priority_queue 的比较器 class

how can I specify the comparator class of priority_queue at runtime

我想创建一个 "generic" priority_queue 它是 class A 的成员,这样我就不需要在编译时指定比较仿函数 class时间。我将在运行时选择比较函子。我怎样才能实现这个目标?下面是我的用例的一个简化示例。

我无法使用任何 C++11 功能。

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);
}

您无法在运行时决定比较器的类型。但是您可以做的是制作一个行为取决于运行时值的比较器。下面是一个适用于您的案例的简单示例:

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;
    }
};

另一个更通用的可能性是使用类似 std::function<bool(T,T)> 的东西,或者(因为你说你不能使用 C++11)boost::function.