-->

C++ - C++ Deque Part 2: Adding and Removing Elements from Deque

Deques allow insertions and deletions from both ends using the following functions:

push_back(value): Adds an element at the back.

push_front(value): Adds an element at the front.

pop_back(): Removes the last element.

pop_front(): Removes the first element.

Example 3: Using push_back() and push_front()

#include

#include

int main() {

    std::deque dq;

    dq.push_back(5);

    dq.push_front(10);

    dq.push_back(15);

    dq.push_front(20);

    for (int num : dq) {

        std::cout << num << " ";

    }

    return 0;

}

Explanation:

push_back(5): Inserts 5 at the end.

push_front(10): Inserts 10 at the front.

push_back(15): Inserts 15 at the back.

push_front(20): Inserts 20 at the front.

The final deque is {20, 10, 5, 15}.

Output:

20 10 5 15

Example 4: Using pop_front() and pop_back()

#include <iostream>

#include <deque>

int main() {

    std::deque<int> dq = {10, 20, 30, 40};

    dq.pop_front(); // Removes 10

    dq.pop_back();  // Removes 40

    for (int num : dq) {

        std::cout << num << " ";

    }

    return 0;

}

Output:

20 30