关于C ++中的队列

时间:2016-05-27 02:53:11

标签: c++ queue push

我使用push in队列将此元素添加到我的队列中但它还没有工作!

#include <iostream>
#include <queue>
using namespace std;

int main() {
    int n,k,tamp;
    cin >> n>> k;
    priority_queue<int,vector<int>,greater<int> > q;
    for(int i=1; i<n; i++)
    {
        cin >> tamp;
        q.push(tamp);
    }
    while(q.top() < k && q.size() > 1)
    {
        tamp = q.top() * 1;
        cout << q.top() << endl;
        q.pop();
        tamp += q.top() * 2;
        cout << q.top() << endl;
        q.pop();

        cout << tamp << endl;

        q.push(tamp);
        while(!q.empty())
        {
            cout << "p=" << q.top() << endl;
            q.pop();
        }
    }
    return 0;
}

这是我的测试:

  1. 8 90
  2. 13 47 74 12 89 74 18 38
  3. 它将变为12 13 18 38 47 74 74 89。 和tamp=12+13*2=38并将其推入队列,但队列只有18 38 47 74 74 89! 帮帮我,谢谢你看这个!!!

1 个答案:

答案 0 :(得分:0)

您有一个可以做的外循环

while(q.top() < k && q.size() > 1)

因此,显然,您希望根据q的内容循环几次。但是,您可以这样做:

while(!q.empty())
{
    cout << "p=" << q.top() << endl;
    q.pop();
}

这将清空队列。因此,它不会循环。

请说明您要做什么。