How to execute a for loop until the queue is empty in C ++

I need to execute a for loop until the queue is empty my code

queue<string> q; for(int i=0;i<q.size(),i++) { // some operation goes here // some datas are added to queue } 
+4
source share
5 answers
 while (!q.empty()) { std::string str = q.front(); // TODO: do something with str. q.pop(); } 
+7
source

This is the same code as the best answer, but using a for loop. It looks cleaner to me.

 for (; !q.empty(); q.pop()) { auto& str = q.front(); // TODO: do something with str. } 
+2
source

Better use a while loop like:

 while (!q.empty()) { // do operations. } 

But if you do this immediately after the queue is declared, you will not get in the loop, because the queue will be empty when created. In this case, you can use a do-while loop like:

 queue<string> q; do { // enqueue and dequeue here. }while (!q.empty()); 
0
source
 while ( ! q.empty() ) { } 
0
source

Yes it is possible.

 int size=q.size(); for(int i=0;i<size;i++){ std::cout<<"\nCell - "<< q.front(); q.pop(); } 

But people in most cases avoid using the for loop, because every time the queue size is checked against the loop counter, where in the middle of n / 2 elements the pop-up iteration will end uncomfortably, since the size will become n / 2, and I will also be n / 2. An example is mentioned below.

 for(int i=0;i<q.size();i++){ std::cout<<"\nCell - "<< q.front(); std::cout<<"\tSize: - "<< q.size()<<" I value:"<<i; q.pop(); } 
0
source

All Articles