Print all elements of a queue in C++ STL

C++ STL | print all elements of a queue: Here, we are going to learn how to print all elements of a Queue in C++ STL?
Submitted by IncludeHelp, on November 27, 2018

To print all elements of a Queue, we follow the following steps:

  1. Run a loop till "queue is not empty".
  2. Print the first (oldest) element by using queue::front() method
  3. Remove the oldest element (perform "pop" operation to remove the element)

Note: This process will remove all elements of the queue as well. The efficient way is discussed below.

1 ) Normal way

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

//Main fubction
int main()
{
	// declaring an empty queue
	queue<int> Q;

	//inserting elements
	Q.push(10);
	Q.push(20);
	Q.push(30);
	cout<<"Queue size before printing the elements: "<<Q.size()<<endl;
	cout<<"Queue element are..."<<endl;
	while(!Q.empty()){
		cout<<" "<<Q.front();
		Q.pop();
	}

	cout<<endl;
	cout<<"Queue size after printing the elements: "<<Q.size()<<endl;

	return 0;
}

Output

Queue size before printing the elements: 3 
Queue element are... 
 10 20 30
Queue size after printing the elements: 0 

Note: See the output, after printing the all elements the size of the Queue is 0 that means all elements have been popped.


2 ) Efficient way

Here, we can create a copy of the Queue and use that copied queue to print the elements and the another best way is to create a function (using call by value) to print the queue, since we know that function takes the copy of the variable and whatever changes happened with the function variable do not affect to the actual variables.

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

//function to print the queue
void printQueue(queue<int> q)
{
	//printing content of queue 
	while (!q.empty()){
		cout<<" "<<q.front();
		q.pop();
	}
	cout<<endl;
}

//Main fubction
int main()
{
	// declaring an empty queue
	queue<int> Q;

	//inserting elements
	Q.push(10);
	Q.push(20);
	Q.push(30);
	cout<<"Queue size before printing the elements: "<<Q.size()<<endl;
	cout<<"Queue element are... "<<endl;
	printQueue(Q);
	cout<<"Queue size after printing the elements: "<<Q.size()<<endl;

	return 0;
}

Output

Queue size before printing the elements: 3 
Queue element are... 
 10 20 30
Queue size after printing the elements: 3




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.