Open In App

How to Push All Elements from a Vector to a Queue in C++?

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to push vector elements into queue
#include <iostream>
#include <queue>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize a vector with some elements
    vector<int> vec = { 1, 2, 3, 4, 5 };
    // Declare a queue
    queue<int> q;
  
    // Iterate through the vector and push elements to the
    // queue
    for (int element : vec) {
        q.push(element);
    }
  
    // Print elements of the queue to verify
    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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads