C ++ LIFO队列,从FIFO到LIFO的简单示例

时间:2018-03-29 10:56:54

标签: c++ stack queue lifo

如何将其转换为LIFO->排在第一位的队列? 有没有简单的方法呢? 这是一个FIFO->第一个队列中的fifo。

using namespace std;

int main(){
    queue<string> q;

    cout << "Pushing one two three four\n";
    q.push("one");
    q.push("two");
    q.push("three");
    q.push("four");

    cout << "Now, retrieve those values in FIFO order.\n";
    while(!q.empty()) {
        cout << "Popping ";
        cout << q.front() << "\n";
        q.pop();
    }
    cout << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:2)

你可以使用堆栈,这是一个LIFO

#include <stack>
#include <string>

using namespace std;
int main()
{
    stack<string> q;

    cout << "Pushing one two three four\n";
    q.push("one");
    q.push("two");
    q.push("three");
    q.push("four");

    cout << "Now, retrieve those values in LIFO order.\n";
    while (!q.empty()) {
        cout << "Popping ";
        cout << q.top() << "\n";
        q.pop();
    }
    cout << endl;

    return 0;
}

Output:
Pushing one two three four
Now, retrieve those values in LIFO order.
Popping four
Popping three
Popping two
Popping one