Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Deque::pop_back() Function



The C++ std::deque::pop_back() function ia used to remove the last element from the deque container. It reduce the size of the deque by one and invalidates references, pointers, or iterators to the popped element.

When we try to invoke pop_back() function on the empty deque, it results in the undefined behaviour.

Syntax

Following is the syntax for std::deque::pop_back() function.

void pop_back();

Parameters

It does not accept any parameters

Return value

This function does not return anything.

Exceptions

Calling this function on empty deque causes undefined behavior.

Time complexity

The time complexity of this function is constant i.e. O(1)

Example

In the following example, we are going to consider the basic usage of the pop_back() function.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    a.pop_back();
    std::cout << "Deque after pop_back(): ";
    for (auto x = a.begin(); x != a.end(); ++x) {
        std::cout << *x << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Deque after pop_back(): A B C 

Example

Consider the following example, where we are going to handle the empty deque.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a;
    if (!a.empty()) {
        a.pop_back();
    } else {
        std::cout << "Deque is empty." << std::endl;
    }
    return 0;
}

Output

Output of the above code is as follows −

Deque is empty.

Example

Let's look at the following example, where we are going to remove the multiple elements from the deque.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    a.pop_back();
    a.pop_back();
    std::cout << "Deque after pop_back(): ";
    for (auto x = a.begin(); x != a.end(); ++x) {
        std::cout << *x << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

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

Deque after pop_back(): A B 
deque.htm
Advertisements