Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - how to copy elements from std::priority_queue to std::vector

Tags:

c++

c++11

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.

like image 405
Shihao Xu Avatar asked Nov 20 '16 20:11

Shihao Xu


1 Answers

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.

like image 199
Shihao Xu Avatar answered Sep 21 '22 13:09

Shihao Xu