The Wayback Machine - https://web.archive.org/web/20241108104551/https://www.geeksforgeeks.org/queue-cpp-stl/
Open In App

Queue in C++ Standard Template Library (STL)

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a specific set of member functions to access its elements.

Following is an example to demonstrate the queue and its various methods.

CPP
// CPP code to illustrate Queue in 
// Standard Template Library (STL)
#include <iostream>
#include <queue>

using namespace std;

// Print the queue
void showq(queue<int> gq)
{
    queue<int> g = gq;
    while (!g.empty()) {
        cout << '\t' << g.front();
        g.pop();
    }
    cout << '\n';
}

// Driver Code
int main()
{
    queue<int> gquiz;
    gquiz.push(10);
    gquiz.push(20);
    gquiz.push(30);

    cout << "The queue gquiz is : ";
    showq(gquiz);

    cout << "\ngquiz.size() : " << gquiz.size();
    cout << "\ngquiz.front() : " << gquiz.front();
    cout << "\ngquiz.back() : " << gquiz.back();

    cout << "\ngquiz.pop() : ";
    gquiz.pop();
    showq(gquiz);

    return 0;
}

Output
The queue gquiz is :     10    20    30

gquiz.size() : 3
gquiz.front() : 10
gquiz.back() : 30
gquiz.pop() :     20    30

Methods of Queue are: 

The time complexity and definition of the following functions are as follows:

queue::empty()O(1)
queue::size()O(1)
queue::emplace()O(1)
queue::front()O(1)
queue::back()O(1)
queue::push(g) O(1)
queue::pop() O(1)
MethodDefinition
queue::empty()Returns whether the queue is empty. It return true if the queue is empty otherwise returns false.
queue::size()Returns the size of the queue.
queue::swap()Exchange the contents of two queues but the queues must be of the same data type, although sizes may differ.
queue::emplace()Insert a new element into the queue container, the new element is added to the end of the queue.
queue::front()Returns a reference to the first element of the queue.
queue::back()Returns a reference to the last element of the queue.
queue::push(g) Adds the element ‘g’ at the end of the queue.
queue::pop() Deletes the first element of the queue.

To master queues and other STL data structures, explore our Complete C++ Course, where you’ll learn how to use queues, stacks, and other data structures efficiently.

C++ program for some more methods

C++
// CPP code to illustrate Queue operations in  STL
// Divyansh Mishra  --> divyanshmishra101010
#include <iostream>
#include <queue>

using namespace std;

// Print the queue
void print_queue(queue<int> q)
{
    queue<int> temp = q;
    while (!temp.empty()) {
        cout << temp.front()<<" ";
        temp.pop();
    }
    cout << '\n';
}

// Driver Code
int main()
{
    queue<int> q1;
    q1.push(1);
    q1.push(2);
    q1.push(3);

    cout << "The first queue is : ";
    print_queue(q1);
  
     queue<int> q2;
    q2.push(4);
    q2.push(5);
    q2.push(6);

    cout << "The second queue is : ";
    print_queue(q2);
  
  
      q1.swap(q2);
      
      cout << "After swapping, the first queue is : ";
    print_queue(q1);
      cout << "After swapping the second queue is : ";
    print_queue(q2);
  
      cout<<q1.empty();  //returns false since q1 is not empty

    return 0;
}

Output
The first queue is : 1 2 3 
The second queue is : 4 5 6 
After swapping, the first queue is : 4 5 6 
After swapping the second queue is : 1 2 3 
0

The time and space complexities of the operations in this code are as follows:

print_queue function:

Time complexity: O(n), where n is the number of elements in the queue.
Space complexity: O(n), where n is the number of elements in the queue.
q1.push(1), q1.push(2), q1.push(3), q2.push(4), q2.push(5), q2.push(6):

Time complexity: O(1) for each push operation.
Space complexity: O(n), where n is the total number of elements in both queues.
q1.swap(q2):

Time complexity: O(1) for each swap operation.
Space complexity: O(1), as this operation only swaps the internal pointers of the two queues.
q1.empty():

Time complexity: O(1), as this operation simply checks if the queue is empty.
Space complexity: O(1), as no extra space is used for this operation.
Overall, the time and space complexities of this code are reasonable and efficient for typical use cases.

Recent Articles on C++ Queue 
  



Similar Reads

Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Multimap in C++ Standard Template Library (STL)
Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap make it very much useful i
6 min read
Deque in C++ Standard Template Library (STL)
Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. Double Ended Queues are basically an implementation of the data structure doub
4 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference ob
2 min read
Sort in C++ Standard Template Library (STL)
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By defa
6 min read
Multiset in C++ Standard Template Library (STL)
Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset: begin() - Returns an iterator to the first element in the multiset --> O(1)end() - Returns an iterator to the theoretical element that follows the last element in th
6 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
9 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is defined inside the <set> header file. Syntax: std:
7 min read
Pair in C++ Standard Template Library (STL)
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples. The pair container is a simple container defined in <utility> header consisting of two data elements or objects. The first element is referen
9 min read
List in C++ Standard Template Library (STL)
Lists are sequence containers that allow non-contiguous memory allocation. As compared to the vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick (constant time). Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward_list. std::
6 min read
Unordered Sets in C++ Standard Template Library
An unordered_set is an unordered associative container implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized. All operations on the unordered_set take constant time O(1) on an average which can go up to linear time O(n) in the worst case which depends on the internally used hash
6 min read
Difference Between STL and Standard Library in C++
In C++, the term "Standard Library" and "Standard Template Library" are often misinterpreted as the same. Although they sound same with only a single word difference, they refer to the different part of the C++ programming language. In this article, we will learn what's the difference between the C++ Standard Library and Standard Template Library (
3 min read
queue::empty() and queue::size() in C++ STL
Queue is a type of container adaptor that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. queue::empty() empty() function is used to check if the queue container is empty or not. SyntaxqueueName.empty()ParametersThis function does not accept any parameter.Return Val
4 min read
queue::front() and queue::back() in C++ STL
Queue are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. queue::front() This function is used to reference the first or the oldest element of the queue container. This function can be used to fetch the first element of a queue.Syn
3 min read
Advantages of circular queue over linear queue
Linear Queue: A Linear Queue is generally referred to as Queue. It is a linear data structure that follows the FIFO (First In First Out) order. A real-life example of a queue is any queue of customers waiting to buy a product from a shop where the customer that came first is served first. In Queue all deletions (dequeue) are made at the front and a
3 min read
Difference Between Linear Queue and Circular Queue
Queues are fundamental data structures in computer science that follow the First-In-First-Out (FIFO) principle. Among the various types of queues, linear queues and circular queues are commonly used. While they share some similarities, they differ significantly in structure and operational efficiency. This article explores the concepts, advantages,
4 min read
Algorithm Library Functions in C++ STL
Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Find element in rangestd :: find_if_not : Find elemen
4 min read
<iterator> library in C++ STL
Iterators in C++ STL | Introduction Functions Iterator operations : std :: advance : Advance iteratorstd :: distance : Return distance between iteratorsstd :: begin : Iterator to beginningstd :: end : Iterator to endstd :: prev : Get iterator to previous elementstd :: next : Get iterator to next elementstd :: next vs std :: advanceAll functions in
1 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
<strings> library in C++ STL
Member functions String.constructor : Construct string object (public member function ).String.destructor : String destructor (public member function )String.operator= : String assignment (public member function ) Iterators Begin : Return iterator to beginning (public member function )End : Return iterator to end (public member function )Advance :
3 min read
<numeric> library in C++ STL
Common mathematical functions std::fabs: This function returns the absolute value. std::sqrt: This function returns the square root std::sin: This function returns the sine measured in radians. Special mathematical functions std::beta: This function evaluates the (complete) Beta integral with given parameters std::hermite: This function Returns the
2 min read
<regex> library in C++ STL
Main classes These classes encapsulate a regular expression and the results of matching a regular expression within a target sequence of characters. basic_regex: Regular expression object (class template) sub_match: Identifies the sequence of characters matched by a sub-expression (class template) match_results: Identifies one regular expression ma
2 min read
queue::swap() in C++ STL
Queue is also an abstract data type or a linear data structure, which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). In a FIFO data structure, the first element added to the queue will be the first one to be removed. queue::swap() swap() function is used to exchange the contents of two queu
2 min read
queue::emplace() in C++ STL
Queue is also an abstract data type or a linear data structure, which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). In a FIFO data structure, the first element added to the queue will be the first one to be removed. queue::emplace() This function is used to insert a new element into the qu
3 min read
C++ STL - Reverse Priority Queue
A priority Queue is an abstract data type that resembles a queue, and each element has a corresponding priority value. Priority queues are built on the top of the max heap and use an array or vector as an internal structure. In C++ STL, by default, the first element of the queue is the greatest of all elements in the queue and elements are in nonin
2 min read
queue push() and pop() in C++ STL
The std::queue::push() and std::queue::pop() functions in C++ STL are used to push the element at the back of the queue and remove the element from the front of the queue respectively. They are the member functions of the std::queue container defined inside the <queue> header file. In this article we will learn how to use queue::push() and qu
2 min read
cerr - Standard Error Stream Object in C++
Standard output stream(cout): cout is the instance of the ostream class. cout is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream(cout) using the insertion operator(<<). Standard error stream (cerr): cerr is the sta
2 min read
Opening Modes in Standard I/O in C/C++ with Examples
Pre-requisites: File Handling in C++ So far the operations using the C program are done on a prompt/terminal that is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be perfo
13 min read
C++ 03 Standard
The C++ programming language, initially developed by Bjarne Stroustrup in 1983, quickly became one of the most popular programming languages due to its efficiency, flexibility, and support for object-oriented programming. However, as the language evolved, variations and extensions introduced by different compiler vendors led to compatibility issues
4 min read
C++ 23 Standard
C++23, officially known as ISO/IEC 14882:2023, is the latest standardized version of the C++ programming language, published in 2023. As C++ introduces new improvements and features every 3 years in the form of a standard like C++20 introduced powerful features such as concepts, ranges, and coroutines, marking a substantial leap in expressiveness a
6 min read
Practice Tags :
three90RightbarBannerImg