Copy one queue to another C++ example

Copy one queue to another C++ program example. Items will be inserted in a std::queue and this queue will be copied to a temporary queue.

One use case is, If we want to process the entire items from a queue but don’t want them to be removed from the queue then we need a temporary queue to process all items. Recommended to read Queue in C++ program with example .

We know that std::queue::front function will return only front element from the queue and does not remove the item. So, no way to traverse all element.

and if we use std::queue::pop function then we can traverse the entire queue but item will be removed from the queue.

Hence use a temporary queue , Get element form the temporary queue using std::queue::front method and pop it out and then process next element etc inside a loop. for example,


            string data = q.front().c_str();

            std::cout << data <<"\n";



Below is complete test C++ program to copy one queue to another queue

* copy one queue to another c++ program

#include <string>
#include <queue>
#include <iostream>
using namespace std;

*Copy original queue to temp queue and process
Elements of the Temp queue will printed and

Finally temp queue will be empty and it will 
not affect original queue and data in original
queue will be found.


void copyQueue(queue<string> tempQ){

cout<<"Temp Queue size: "<<tempQ.size()<<endl;
 //iterate the queue, print elements and 
 //pop the element - on pop element will be removed \
 //from queue
 cout << "Fruits are: "<<endl;
 string data = tempQ.front().c_str();
 std::cout << data <<"\n";


int main()
 //Create a queue
 queue<string> fruitsQueue;

 *Insert elements in to the queue
 cout << "Inserting elements into Queue\n";

cout<< "Original queue size: "<<fruitsQueue.size()<<endl;

//copy queue to another queue

 *Check if original queue contains and elements
 and not popped by temp queue
 cout<< "Original queue size: "<<fruitsQueue.size()<<endl;;

//Process orinial queue
 cout << "Fruits are: "<<endl;
 while(!fruitsQueue.empty()) {

//front() function returns firsts element
 //but does not delete it from queue
 cout <<fruitsQueue.front() << "\n";

//To delete front element from the queue.

cout << endl;

return 0;

Related Posts