【问题标题】:how can I specify the comparator class of priority_queue at runtime如何在运行时指定priority_queue的比较器类
【发布时间】:2017-02-28 21:25:26
【问题描述】:

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

我无法使用任何 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);
}

【问题讨论】:

  • std::function 作为比较器怎么样,因为它已经实现了类型擦除,而这正是您可能需要的。编辑:抱歉没有注意到“我不能使用 C++11”。天哪,它的 2017 年已经...

标签: c++ priority-queue comparator


【解决方案1】:

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

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&lt;bool(T,T)&gt; 之类的东西,或者(因为你说你不能使用 C++11)boost::function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多