How to Push All Elements from a Vector to a Queue in C++?
Last Updated :
09 Feb, 2024
In C++, vectors are dynamic arrays while the queue is a data structure that follows the FIFO (First In First Out) property. In this article, we will learn how to push all elements from a vector to a queue in C++.
Example
Input:
myVector = {1, 5, 8, 9, 4}
Output:
myQueue = 1 5 8 9 4
Copy All Vector Elements into the Queue in C++
We cannot directly push all the elements of the vector into the queue. We have to push them one by one. We can create a loop to iterate through the vector and keep pushing each element into the queue using the std::queue::push() function.
C++ Program to Push Vector Elements into a Queue
The below example demonstrates how we can push all vector elements into a queue.
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 1, 2, 3, 4, 5 };
queue< int > q;
for ( int element : vec) {
q.push(element);
}
cout << "Elements in the queue: " ;
while (!q.empty()) {
cout << q.front() << " " ;
q.pop();
}
return 0;
}
|
Output
Elements in the queue: 1 2 3 4 5
Time Complexity: O(N)
Auxiliary Space: O(N)
Note: We can also use queue constructor in C++23 to directly construct a queue and initializing it with vector elements.
Share your thoughts in the comments
Please Login to comment...