我试图理解下面的代码
我认为,由于 HackedQueue 是从priority_queue 私有派生的,因此它可以访问其私有。所以,我假设*&HackedQueue::c返回基类对象的地址,并为 q 调用它。但尚不完全清楚,甚至更不清楚它如何成为有效的语法。
提到priority_queue,我想知道是否仍然没有更干净的解决方法。例如,此链接上的第四个 c'tor
priority_queue( const Compare& compare, Container&& cont );
https://en.cppreference.com/w/cpp/container/priority_queue/priority_queue
似乎提供了一个可以使用的容器,而不是作为只读输入。我在 Visual Studio 头文件中没有看到它,而且我不清楚&&.
相关的是,我不明白相反的问题,例如为什么我需要访问私有容器,它不是为此而设计的。那么,如何调试优先级队列,其中基本需求是打印其元素?
#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;
}
Run Code Online (Sandbox Code Playgroud)
我试图理解下面的代码
分点来说吧:
.*是指向成员的指针访问运算符。请参阅https://en.cppreference.com/w/cpp/language/operator_member_accesspriority_queue,它使用队列使用的底层容器来存储数据并使用protected名称为 的成员访问该数据c。
class priority_queue
{
...
protected:
// See queue::c for notes on these names.
_Sequence c;
_Compare comp;
Run Code Online (Sandbox Code Playgroud)
请参阅queue::c 中的注释了解为什么它被命名为c。和C++98标准。
HackedQueue继承自,priority_queue以便它可以访问它的protected成员,&HackedQueue::cc是指向类中成员的指针HackedQueue(它继承自priority_queue),q.*(&HackedQueue::c);使用指向成员的指针访问c对象中的该成员,qq。什么是 &&。
右值引用声明符。请参阅https://en.cppreference.com/w/cpp/language/reference
如何调试优先级队列,其中基本需求是打印其元素?
用调试器。无论如何,这个问题也在链接的问题How to iterate over apriority_queue?中得到了解答。。
| 归档时间: |
|
| 查看次数: |
263 次 |
| 最近记录: |