2017-02-28 38 views
0

我想创建一个属于类A成员的“通用”priority_queue,这样我就不需要在编译时指定比较器函子类。我将在运行时选择比较器通道。我怎样才能达到这个目标?下面是我的用例的一个简单例子。如何在运行时指定priority_queue的比较器类

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

如何将std :: function作为比较器,因为它已经实现了类型擦除,而这正是您可能需要的。编辑:抱歉,没有注意到'我不能使用C++ 11'。 Geez 2017年已经... –

回答

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

另一种更通用的方法可行就可以使用像这样,或东西(因为你说你不能使用C++ 11)boost::function