Initializing a Deque from a Vector in C++
The most efficient way to initialize a deque from a vector in C++ is using the Range Constructor provided by the std::deque class. The constructor takes two iterators which represent the beginning and the end of the range of elements to be copied in the deque and copies them easily inside the deque from the vector.
C++ Program to Initialize a Deque Using a Vector
C++
// C++ program to Initialize a Deque from a Vector #include <deque> #include <iostream> #include <vector> using namespace std; int main() { vector< int > vec = { 10, 20, 30, 40, 50 }; // Print the elements of the vector cout << "Elements in Vector:" ; for ( int num : vec) { cout << num << " " ; } cout << endl; // Initialize a deque from vector using range // constructor deque< int > Dq(vec.begin(), vec.end()); // Print elements of deque cout << "Elements in Deque:" ; for ( int num : Dq) { cout << num << " " ; } cout << endl; return 0; } |
Elements in Vector:10 20 30 40 50 Elements in Deque:10 20 30 40 50
Time Complexity: O(N) where N is the total number of elements in the vector
Auxiliary Space: O(N)
How to Initialize a Deque from a Vector in C++?
In C++, the Standard Template Library(STL) provides a container deque also known as a double-ended queue where insertion and deletions are possible from both ends. On the other hand, vectors are dynamic containers that can resize themselves during the insertion or deletion of elements. In this article, we will learn how to initialize a deque using a vector in C++.
Example
Input: myVector = {1, 4, 5, 9, 7} Output: myDequeu = {1 4 5 9 7}