【发布时间】: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