C++ LIFO queue, easy simple example from FIFO to LIFO

Dennis Vymer picture Dennis Vymer · Mar 29, 2018 · Viewed 9.7k times · Source

How can I make this to a LIFO-> last in first out queue? Is there any easy way to do so? This is a FIFO-> fifo in first out queue.

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;
}

Answer

schorsch_76 picture schorsch_76 · Mar 29, 2018

You can use a stack, this is a 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