how to execute an for loop till the queue is emptyin c++
10,039
Solution 1
while (!q.empty())
{
std::string str = q.front();
// TODO: do something with str.
q.pop();
}
Solution 2
It's the same code as the best answer, but using for
loop. It looks cleaner for me.
for (; !q.empty(); q.pop())
{
auto& str = q.front();
// TODO: do something with str.
}
Related videos on Youtube
Author by
raja
Updated on June 04, 2022Comments
-
raja almost 2 years
i need to execute an for loop till 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 }
-
ADreNaLiNe-DJ almost 7 yearsPlease add explanations to your answer.
-
LemonCool over 6 yearsfor loop doesn't need to instance/initiate a variable, so we just use ';' to tell it do nothing, the condition of the for is until the queue is not empty, at the end of the loop; pop the item from the queue
-
yuqli almost 6 yearsWhy we need the
&
here? -
Virus_7 over 5 yearsIt's kind of optimisation.
std::queue::front()
returns a reference to the element that's why there's&
. We usually don't need an object copy, we can manipulate the string in-place, as we're popping it out later.