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.
}
Share:
10,039

Related videos on Youtube

raja
Author by

raja

Updated on June 04, 2022

Comments

  • raja
    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
    ADreNaLiNe-DJ almost 7 years
    Please add explanations to your answer.
  • LemonCool
    LemonCool over 6 years
    for 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
    yuqli almost 6 years
    Why we need the & here?
  • Virus_7
    Virus_7 over 5 years
    It'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.

Related