C++ Initialize a Deque

www.ig‮fi‬tidea.com

You can initialize a deque in C++ using the initialization list syntax or by copying elements from another container. Here are examples of both methods:

  1. Initialization list syntax:
#include <deque>
#include <iostream>

int main() {
    std::deque<int> d {1, 2, 3, 4, 5}; // create a deque with 5 elements

    for (int i : d) {
        std::cout << i << " "; // output the elements of the deque
    }
    std::cout << std::endl;

    return 0;
}

Output:

1 2 3 4 5

In this example, we use the initialization list syntax to create a deque d with five elements.

  1. Copying from another container:
#include <deque>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> v {1, 2, 3, 4, 5}; // create a vector with 5 elements
    std::deque<int> d(v.begin(), v.end()); // create a deque by copying elements from the vector

    for (int i : d) {
        std::cout << i << " "; // output the elements of the deque
    }
    std::cout << std::endl;

    return 0;
}

Output:

1 2 3 4 5

In this example, we create a vector v with five elements using the initialization list syntax. We then create a deque d by copying elements from the vector using the constructor that takes two iterators, v.begin() and v.end(). This constructor copies the elements between the two iterators into the deque d.

These are two ways to initialize a deque in C++. You can choose the method that best suits your needs depending on whether you want to create a deque with a fixed set of initial values or copy elements from another container.