Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. C++ Dictionary
  3. std::stack / std::queue

std::stack / std::queue

The C++ Standard Template Library (STL) provides std::stack, std::queue, and std::priority_queue as container adaptors for LIFO, FIFO, and priority-ordered access respectively. Each one wraps an internal container and exposes only the interface suited to its specific use case.

Syntax

// ========================================
// Basic syntax for stack / queue / priority_queue
// ========================================

#include <stack>           // required for std::stack
#include <queue>           // required for std::queue and std::priority_queue

// ----------------------------------------
// std::stack (LIFO: last in, first out)
// ----------------------------------------
std::stack<int> st;

st.push(10);        // push element onto the top
st.push(20);
st.top();           // peek at the top element (does not remove it)
st.pop();           // remove the top element
st.size();          // returns the number of elements
st.empty();         // returns true when empty

// ----------------------------------------
// std::queue (FIFO: first in, first out)
// ----------------------------------------
std::queue<int> q;

q.push(10);         // enqueue at the back
q.push(20);
q.front();          // peek at the front element (does not remove it)
q.back();           // peek at the back element (does not remove it)
q.pop();            // remove the front element
q.size();           // returns the number of elements
q.empty();          // returns true when empty

// ----------------------------------------
// std::priority_queue (priority-ordered queue)
// Default is a max-heap (largest value has highest priority)
// ----------------------------------------
std::priority_queue<int> pq;

pq.push(30);        // insert element (heap is restructured automatically)
pq.push(10);
pq.push(50);
pq.top();           // peek at the highest-priority element (max value)
pq.pop();           // remove the highest-priority element
pq.size();          // returns the number of elements
pq.empty();         // returns true when empty

// For a min-heap, pass greater<T> as the comparator
std::priority_queue<int, std::vector<int>, std::greater<int>> minPQ;

Member Function Reference

ContainerMember functionDescription
stackpush(val)Pushes an element onto the top.
stackpop()Removes the top element. Returns void.
stacktop()Returns a reference to the top element. Does not remove it.
queuepush(val)Enqueues an element at the back.
queuepop()Removes the front element. Returns void.
queuefront()Returns a reference to the front element. Does not remove it.
queueback()Returns a reference to the back element. Does not remove it.
priority_queuepush(val)Inserts an element. The internal heap is restructured automatically.
priority_queuepop()Removes the highest-priority element (max value by default).
priority_queuetop()Returns a reference to the highest-priority element. Does not remove it.
commonsize()Returns the current number of elements.
commonempty()Returns true when the container has zero elements.

Sample Code

kof_containers.cpp
// ========================================
// kof_containers.cpp
// Demonstrates stack, queue, and priority_queue
// using KOF (THE KING OF FIGHTERS) characters
// ========================================

#include <iostream>
#include <stack>
#include <queue>
#include <string>

// ========================================
// Struct holding fighter information
// ========================================
struct Fighter {
    std::string name;    // character name
    int         power;   // battle power (used as sort key for priority_queue)

    // Operator overload for priority_queue comparison
    // Higher power means higher priority
    bool operator<(const Fighter& other) const {
        return power < other.power;
    }
};

// ========================================
// Helper function to print fighter info on one line
// ========================================
void printFighter(const Fighter& f) {
    std::cout << f.name << " (power: " << f.power << ")" << std::endl;
}

int main() {

    // ========================================
    // 1. std::stack demo (LIFO)
    //    Stack combo moves and pop them in reverse order
    // ========================================
    std::cout << "=== std::stack demo (LIFO) ===" << std::endl;

    std::stack<std::string> comboStack;

    // Push Kusanagi Kyo's combo moves in order
    comboStack.push("Hasshūhai");       // 1st move pushed
    comboStack.push("Yuri-ori");        // 2nd move pushed
    comboStack.push("Kagura Muhou");    // 3rd move pushed (now on top)

    std::cout << "Kusanagi Kyo's combo stack (" << comboStack.size() << " moves)" << std::endl;

    // Pop in LIFO order (last pushed comes out first)
    while (!comboStack.empty()) {
        std::cout << "  pop: " << comboStack.top() << std::endl;
        comboStack.pop();
    }
    std::cout << std::endl;

    // ========================================
    // 2. std::queue demo (FIFO)
    //    Characters queue up for a match; first in line fights first
    // ========================================
    std::cout << "=== std::queue demo (FIFO) ===" << std::endl;

    std::queue<std::string> waitQueue;

    // Characters join the queue in this order
    waitQueue.push("Terry Bogard");     // 1st in line
    waitQueue.push("Andy Bogard");      // 2nd in line
    waitQueue.push("Shiranui Mai");     // 3rd in line
    waitQueue.push("Yagami Iori");      // 4th in line

    std::cout << "Wait queue (front: " << waitQueue.front()
              << "  back: " << waitQueue.back() << ")" << std::endl;

    // Call characters in FIFO order (first in line fights first)
    int callOrder = 1;
    while (!waitQueue.empty()) {
        std::cout << "  Match " << callOrder << ": " << waitQueue.front() << std::endl;
        waitQueue.pop();
        callOrder++;
    }
    std::cout << std::endl;

    // ========================================
    // 3. std::priority_queue demo (max-heap)
    //    Characters with higher power enter first
    // ========================================
    std::cout << "=== std::priority_queue demo (max-heap) ===" << std::endl;

    std::priority_queue<Fighter> pq;

    // Register KOF team battle powers (added in arbitrary order)
    pq.push({"Kusanagi Kyo",  9500});
    pq.push({"Yagami Iori",   9800});
    pq.push({"Terry Bogard",  8700});
    pq.push({"Andy Bogard",   8200});
    pq.push({"Shiranui Mai",  8500});

    std::cout << "Power ranking:" << std::endl;

    int rank = 1;
    while (!pq.empty()) {
        std::cout << "  Rank " << rank << ": ";
        printFighter(pq.top());   // peek at the highest-power fighter
        pq.pop();                 // after popping, the next highest becomes top()
        rank++;
    }
    std::cout << std::endl;

    // ========================================
    // 4. Min-heap (lowest power enters first)
    //    Specify std::greater<Fighter> for a min-heap
    // ========================================
    std::cout << "=== Min-heap (lowest power first) ===" << std::endl;

    std::priority_queue<Fighter, std::vector<Fighter>, std::greater<Fighter>> minPQ;

    minPQ.push({"Kusanagi Kyo",  9500});
    minPQ.push({"Yagami Iori",   9800});
    minPQ.push({"Terry Bogard",  8700});
    minPQ.push({"Andy Bogard",   8200});
    minPQ.push({"Shiranui Mai",  8500});

    std::cout << "Handicap match (weakest first):" << std::endl;

    rank = 1;
    while (!minPQ.empty()) {
        std::cout << "  Rank " << rank << ": ";
        printFighter(minPQ.top());
        minPQ.pop();
        rank++;
    }

    return 0;
}
# Compile
g++ -std=c++11 kof_containers.cpp -o kof_containers

# Run
./kof_containers
=== std::stack demo (LIFO) ===
Kusanagi Kyo's combo stack (3 moves)
  pop: Kagura Muhou
  pop: Yuri-ori
  pop: Hasshūhai

=== std::queue demo (FIFO) ===
Wait queue (front: Terry Bogard  back: Yagami Iori)
  Match 1: Terry Bogard
  Match 2: Andy Bogard
  Match 3: Shiranui Mai
  Match 4: Yagami Iori

=== std::priority_queue demo (max-heap) ===
Power ranking:
  Rank 1: Yagami Iori (power: 9800)
  Rank 2: Kusanagi Kyo (power: 9500)
  Rank 3: Terry Bogard (power: 8700)
  Rank 4: Shiranui Mai (power: 8500)
  Rank 5: Andy Bogard (power: 8200)

=== Min-heap (lowest power first) ===
Handicap match (weakest first):
  Rank 1: Andy Bogard (power: 8200)
  Rank 2: Shiranui Mai (power: 8500)
  Rank 3: Terry Bogard (power: 8700)
  Rank 4: Kusanagi Kyo (power: 9500)
  Rank 5: Yagami Iori (power: 9800)

Common Mistakes

Calling top()/front()/pop() on an empty container

Calling top(), front(), or pop() when empty() is true (zero elements) causes undefined behavior. The program may crash or return a garbage value. Always check empty() before calling these functions.

NG example
#include <iostream>
#include <stack>
#include <string>

int main() {
    std::stack<std::string> comboStack;

    // Calling top() with nothing pushed is undefined behavior
    std::cout << comboStack.top() << std::endl;  // NG
    comboStack.pop();  // NG: calling pop() on an empty stack is also undefined behavior

    return 0;
}

OK example: Check empty() before operating.

#include <iostream>
#include <stack>
#include <string>

int main() {
    std::stack<std::string> comboStack;

    // Push Kusanagi Kyo's combo moves
    comboStack.push("Hasshūhai");
    comboStack.push("Yuri-ori");
    comboStack.push("Kagura Muhou");

    // Always check empty() before calling top()/pop()
    while (!comboStack.empty()) {
        std::cout << comboStack.top() << std::endl;
        comboStack.pop();
    }

    // Do not call top() here — the stack is now empty
    if (!comboStack.empty()) {
        std::cout << comboStack.top() << std::endl;
    } else {
        std::cout << "The stack is empty." << std::endl;
    }

    return 0;
}
# Compile
g++ -std=c++11 ok_stack_empty.cpp -o ok_stack_empty

# Run
./ok_stack_empty
Kagura Muhou
Yuri-ori
Hasshūhai
The stack is empty.

Trying to retrieve a value from pop()

pop() only removes an element and returns nothing (void). To obtain the value, first read it with top() or front(), then call pop() to remove it — two separate steps.

NG example (compile error)
#include <stack>
#include <string>

int main() {
    std::stack<std::string> comboStack;
    comboStack.push("Hasshūhai");

    // NG: pop() returns void; you cannot capture its return value
    std::string move = comboStack.pop();  // compile error
    return 0;
}

OK example: Read the value with top(), then remove it with pop().

#include <iostream>
#include <stack>
#include <string>

int main() {
    std::stack<std::string> comboStack;
    comboStack.push("Hasshūhai");
    comboStack.push("Yuri-ori");

    // Read the value with top(), then remove it with pop()
    std::string move = comboStack.top();  // get the value
    comboStack.pop();                      // then remove it
    std::cout << "Popped move: " << move << std::endl;
    return 0;
}
# Compile
g++ -std=c++11 ok_stack_pop.cpp -o ok_stack_pop

# Run
./ok_stack_pop
Popped move: Yuri-ori

Overview

std::stack, std::queue, and std::priority_queue are all "container adaptors" — they wrap an underlying container such as std::deque or std::vector and expose only a limited interface suited to their purpose. std::stack is LIFO (last in, first out) and is well suited to implementing function call stacks or depth-first search (DFS). std::queue is FIFO (first in, first out) and is ideal for task queues or breadth-first search (BFS). std::priority_queue maintains an internal heap structure with O(log n) for insert and removal and O(1) for accessing the highest-priority element. By default it is a max-heap; passing std::greater<T> as the third template argument converts it to a min-heap. When using a struct as the element type, either overload operator< or provide a comparator function object. Note that none of these three container adaptors provide iterators, so they cannot be used directly with STL algorithm functions like std::sort. Consider using std::vector when random access or full traversal is needed.

If you find any errors or copyright issues, please .