根据具体情况,我需要在同一vector<Objects>
priority_queue<Object, vector<Object>> pq;
if (something...)
priority_queue<Object, vector<Object>, Comp1> pq;
else if(...)
priority_queue<Object, vector<Object>, Comp2> pq;
else
priority_queue<Object, vector<Object>, Comp3> pq;
... All further code works on pq & does not change on the conditions.
我如何实现这一目标?我发现不建议更改比较器,因为它会导致未定义的行为,但在这里我只需要根据某些条件初始化不同的comp。
答案 0 :(得分:4)
使用std::function<bool(Object const&, Object const&)>
作为比较器,然后在构造期间传入适当的仿函数。
//typedef just void repeating myself over and over
typedef priority_queue<Object, vector<Object>, std::function<bool(Object const&, Object const&)>> queue_type;
queue_type pq;
if (something...)
pq = queue_type{std::less<Object>{}};
else if(...)
pq = queue_type{std::greater<Object>{}};
else
pq = queue_type{...};
注意,在构造队列期间未能提供有效的比较函数将导致在进行任何依赖于比较的操作时抛出异常。
答案 1 :(得分:2)
作为替代方案,您可以将代码重写为:
template <typename Comp>
void foo()
{
priority_queue<Object, vector<Object>, Comp> pq;
// ... All further code works on pq & does not change on the conditions.
}
然后
if (something...) {
foo<Comp1>>();
} else if(...) {
foo<Comp2>>();
} else {
foo<Comp3>>();
}