Introduction to Queues and std::queue

Queue vs Stack: What's the Difference?

What is the main difference between a queue and a stack data structure in C++?

Vector art representing computer hardware

The main difference between a queue and a stack lies in the order in which elements are added and removed:

  • In a queue, elements follow the First-In-First-Out (FIFO) principle. The first element added to the queue will be the first one to be removed. Queues are often compared to a line of people waiting for a service, where the person who joins the line first gets served first.
  • In a stack, elements follow the Last-In-First-Out (LIFO) principle. The last element added to the stack will be the first one to be removed. Stacks are often compared to a stack of plates, where the last plate placed on top of the stack is the first one to be removed.

In C++, the standard library provides the std::queue class template for queues and the std::stack class template for stacks. Both are container adaptors, meaning they use an underlying container to store the elements.

Here's an example illustrating the difference between a queue and a stack:

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

int main() {
  std::queue<int> myQueue;
  myQueue.push(1);
  myQueue.push(2);
  myQueue.push(3);

  std::stack<int> myStack;
  myStack.push(1);
  myStack.push(2);
  myStack.push(3);

  // Output: 1
  std::cout << "Queue front: "
    << myQueue.front() << std::endl;

  // Output: 3
  std::cout << "Stack top: "
    << myStack.top() << std::endl;
}
Queue front: 1
Stack top: 3

In this example, the first element added to the queue (1) is the first one to be accessed using myQueue.front(), while the last element added to the stack (3) is the first one to be accessed using myStack.top().

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved