为了获得更好的性能,您可以从队列中“窃取”底层容器,合并它们并从合并的容器中构造另一个,而不是像之前建议的那样逐个处理它们priority_queue
:
// https://stackoverflow.com/a/1385520/8414561
template <class T, class S, class C>
S& Container(std::priority_queue<T, S, C>& q) {
struct HackedQueue : private std::priority_queue<T, S, C> {
static S& Container(std::priority_queue<T, S, C>& q) {
return q.*&HackedQueue::c;
}
};
return HackedQueue::Container(q);
}
int main()
{
std::priority_queue<int> queue1{std::less<int>{}, {1,2,3,4,5,6,7}};
std::priority_queue<int> queue2{std::less<int>{}, {10,14,15}};
auto v1 = std::move(Container(queue1));
auto v2 = std::move(Container(queue2));
v1.insert(v1.end(), std::make_move_iterator(v2.begin()), std::make_move_iterator(v2.end()));
std::priority_queue<int>queue3{std::less<int>{}, std::move(v1)};
while (!queue3.empty()) {
std::cout << queue3.top() << std::endl;
queue3.pop();
}
}
活生生的例子。