如何在 c++ 中执行 for 循环直到队列为空
我需要执行 for 循环直到队列为空 我的代码
queue<string> q;
for(int i=0;i<q.size(),i++)
{
// some operation goes here
// some datas are added to queue
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它与最佳答案的代码相同,但使用
for
循环。对我来说看起来更干净。It's the same code as the best answer, but using
for
loop. It looks cleaner for me.最好使用 while 循环:
但是,如果您在声明队列后立即执行此操作,您将不会进入循环,因为队列在创建时将为空。在这种情况下,您可以使用 do-while 循环:
Its better to use a while loop as:
But if you do this immediately after declaring the queue you'll not get in the loop as the queue will be empty on creation. In that case you can use a do-while loop as:
是的,这是可能的。
但人们大多避免使用 for 循环,因为每次队列的大小都会根据循环计数器进行检查,在 n/2 个元素中间弹出迭代将突然结束,因为大小将变为 n/2 并且 i 也是 n/ 2.下面提到的例子。
Yes its possible.
But people mostly avoid using for loop because, every time size of queue will be checked against loop counter, where in the middle of n/2 elemets pop up iteration will end up ubruptly as size will become n/2 and i is also n/2. Example mentioned below.