I'm trying to understand the code below from
How to iterate over a priority_queue?
I gather that since HackedQueue is deriving privately from priority_queue, it can access its privates. So, I assume that *&HackedQueue::c
returns the address of the base class object, and its called for q. Not fully clear, though, and even more how it's a valid syntax.
Mentioning priority_queue, I was wondering if there's still no cleaner workaround. For example, the 4th c'tor on this link
priority_queue( const Compare& compare, Container&& cont );
https://en.cppreference.com/w/cpp/container/priority_queue/priority_queue
seems to provide a container to work with and not as read only input. I don't see it though in visual studio header file, and I'm not clear what is &&
.
Related, I don't understand opposing questions such as why I need access to the private container, it's not made for that. Well, how do you debug a priority queue, where the basic need is to print its elements?
#include <queue>
#include <cstdlib>
#include <iostream>
using namespace std;
template <class T, class S, class C>
S& Container(priority_queue<T, S, C>& q) {
struct HackedQueue : private priority_queue<T, S, C> {
static S& Container(priority_queue<T, S, C>& q) {
return q.*&HackedQueue::c;
}
};
return HackedQueue::Container(q);
}
int main()
{
priority_queue<int> pq;
vector<int> &tasks = Container(pq);
cout<<"Putting numbers into the queue"<<endl;
for(int i=0;i<20;i++){
int temp=rand();
cout<<temp<<endl;
pq.push(temp);
}
cout<<endl<<"Reading numbers in the queue"<<endl;
for(vector<int>::iterator i=tasks.begin();i!=tasks.end();i++)
cout<<*i<<endl;
cout<<endl<<"Taking numbers out of the queue"<<endl;
while(!pq.empty()){
int temp=pq.top();
pq.pop();
cout<<temp<<endl;
}
return 0;
}