How to Initialize a Deque from a Vector in C++?
Last Updated :
15 Feb, 2024
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}
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++
#include <deque>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 10, 20, 30, 40, 50 };
cout << "Elements in Vector:" ;
for ( int num : vec) {
cout << num << " " ;
}
cout << endl;
deque< int > Dq(vec.begin(), vec.end());
cout << "Elements in Deque:" ;
for ( int num : Dq) {
cout << num << " " ;
}
cout << endl;
return 0;
}
|
Output
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)
Share your thoughts in the comments
Please Login to comment...