C++ Queue::back() Function



The C++ std::queue::back() function is used to access the last element of a queue without removing it. It allows access to the element that was recently added, providing a way to read or modify the element. The time complexity of this function is 0(1). This function is commonly used when there is a need to modify the recently added element of the queue.

When this function is invoked on the empty queue it results in the undefined behaviour.

Syntax

Following is the syntax for std::queue::back() function.

reference& back();const_reference& back() const;

Parameters

This does not accepts any parameters.

Return value

This function returns the reference to the last element of the queue.

Example

Let's look at the following example, where we are going to demonstrate the basic usage of back() function.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    a.push(11);
    a.push(22);
    a.push(33);
    std::cout << "The last element is: " << a.back() << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

The last element is: 33

Example

Consider the another scenario, where we are going to modify the last element using the back() function.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    a.push(1);
    a.push(2);
    a.back() = 11;
    std::cout << "After modification the last element is : " << a.back() << std::endl;
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

After modification the last element is : 11

Example

In the following example, we are going to use the back() function in the loop.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    for (int x = 1; x <= 5; ++x) {
        a.push(x * 2);
        std::cout << "" << a.back() << std::endl;
    }
    return 0;
}

Output

Output of the above code is as follows −

2
4
6
8
10

Example

Following is an example where we initially check whether the queue is empty or not, then add the elements to the queue and apply the back() function.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    if (!a.empty()) {
        std::cout << "The last element is: " << a.back() << std::endl;
    } else {
        std::cout << "The queue is empty" << std::endl;
    }
    a.push(1);
    a.push(2);
    if (!a.empty()) {
        std::cout << "After adding elements, the last element is: " << a.back() << std::endl;
    }
    return 0;
}

Output

If we run the above code it will generate the following output −

The queue is empty
After adding elements, the last element is: 2
queue.htm
Advertisements