-->

C++ - C++ Queues Part 1: Introduction to Queues

A queue is a linear data structure that follows the FIFO principle, meaning the first element added is the first to be removed. The main operations of a queue are:

push() – Adds an element to the back of the queue.

pop() – Removes an element from the front.

front() – Returns the element at the front.

back() – Returns the last element.

empty() – Checks if the queue is empty.

size() – Returns the number of elements in the queue.

Examples

Declaring and Initializing a Queue

#include <iostream>

#include <queue>

int main() {

    std::queue<int> myQueue; // Creates an empty queue

    return 0;

}

Explanation: A queue is declared using std::queue<int>, where int is the type of elements it holds.

Adding Elements (push())

myQueue.push(10);

myQueue.push(20);

myQueue.push(30);

Explanation: Elements are added to the back of the queue.

Checking Queue Size (size())

std::cout << "Queue size: " << myQueue.size(); // Output: 3

Explanation: The size() method returns the current number of elements in the queue.