简体   繁体   中英

Can I use member function of underlying container of priority_queue

As title, I created a priority_queue(default use vector as underlying container) p. Can I use vector's member function like p.push_back(a) or p.reserve(25) or even use for(auto i:p) {cout << i} When I run code below , the compiler(GCC) tell me

class "std::priority_queue>, >" has no member "reserve"
class std::priority_queue, std::greater >' has no member named 'begin'
etc.

How should I do to if i want to use the function mentioned above, or they are just forbidden?

#include<iostream>
#include<queue>
#include<vector>

using namespace std;

int main(){
    priority_queue<int , vector<int>, greater<int>> p;
    p.push_back(1);
    p.reserve(25);
    for(auto i : p){
        cout << i;
    }
    return 0;
}

The container adapters are designed specifically to abstract away the underlying container. It provides a new abstraction on its own.

So, no, you cannot call members of the vector inside the queue. What you can do however, is call functions on the vector before it enters the queue. And then move it in place:

#include<iostream>
#include<queue>
#include<vector>

using namespace std;

int main(){
   vector<int>   v;
   v.reserve(25);
   v.push_back(1);

    priority_queue<int , vector<int>, greater<int>> p(greater<int>(), std::move(v));

    return 0;
} 

Still no way to output the contents of a queue or stack, as you can only access the top() element (on purpose, as part of the abstraction).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM