For example, I want to pick out the k-th largest elements from a input vector.
I know it can be better done with QuickSelect std::nth_element.
My question is how to copy the underlying container std::vector of std::priority_queue to another vector, rather than solve this coding problem.
priority_queue<int, vector<int>, greater<int>> pq;
for (int num : nums) {
pq.push(num);
if (pq.size() > k) {
pq.pop();
}
}
My way is stupid:
vector<int> res;
while (!pq.empty()) {
res.push_back(pq.top());
pq.pop();
}
Is there better way to do it?
Can we do it like
vector<int> res = pq;
The top k elements do not need to be ordered.
You could use vector<int>
at the beginning.
And treat this vector as heap, with std::make_heap
, std::push_heap
, std::pop_heap
.
That way, you can copy the vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With