c++ - How to maintain a reference to a std::priority_queue's container? -


i'm creating std::priority_queue using std::vector container.

it seems priority queue creates copy of container passed in constructor, since changes made container after constructing queue aren't reflected in queue's container.

for example, if call clear() on container, priority queue remains full.

is there way maintain reference priority queue's internal container after construction?

std::priority_queue 1 of few standard containers designed derived from.

it has protected member c container.

you can derived queue , use c in derived class.

if mutate container, remember it's heap , needs have appropriate heap functions applied before leave method.

#include <queue> #include <algorithm>  struct my_special_queue : std::priority_queue<int> {     using underlying_queue = std::priority_queue<int>;      // re-use constructors     using underlying_queue::underlying_queue;      // add clear method      void clear()     {         underlying_queue::c.clear();     }      void remove_all_odd_numbers()     {         c.erase(std::remove_if(c.begin(), c.end(),                                  [](auto&&x) { return (x % 2) == 1; }),                                  c.end());         std::make_heap(c.begin(), c.end(),                          underlying_queue::comp);     }  };  int main() {     my_special_queue q;      // standard priority_queue methods     q.push(1);     q.push(2);     q.push(9);     q.push(6);     q.push(4);     q.push(7);      if (not q.empty()) {         q.top();         q.pop();     }      // apply our custom functions         q.clear();     q.remove_all_odd_numbers(); } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -