如何在c ++中使用优先级队列?

dat*_*ili 0 c++ priority-queue

例如,我们有priority_queue<int> s;一些元素.以下代码的正确形式是什么:

while (!s.empty()) {
    int t=s.pop();// this does not retrieve the value from the queue
    cout<<t<<endl;
}
Run Code Online (Sandbox Code Playgroud)

GMa*_*ckG 7

请参阅您的文档,您将看到pop没有返回值.这有多种原因,但那是另一个话题.

适当的形式是:

while (!s.empty())
{
    int t = s.top();
    s.pop();

    cout << t << endl;
}
Run Code Online (Sandbox Code Playgroud)

要么:

for (; !s.empty(); s.pop())
{
    cout << s.top(); << endl;
}
Run Code Online (Sandbox Code Playgroud)