【发布时间】:2010-10-07 05:55:09
【问题描述】:
我需要执行一个 for 循环,直到队列为空 我的代码
queue<string> q;
for(int i=0;i<q.size(),i++)
{
// some operation goes here
// some datas are added to queue
}
【问题讨论】:
标签: c++ string stl loops queue
我需要执行一个 for 循环,直到队列为空 我的代码
queue<string> q;
for(int i=0;i<q.size(),i++)
{
// some operation goes here
// some datas are added to queue
}
【问题讨论】:
标签: c++ string stl loops queue
while (!q.empty())
{
std::string str = q.front();
// TODO: do something with str.
q.pop();
}
【讨论】:
与最佳答案的代码相同,但使用for 循环。它对我来说看起来更干净。
for (; !q.empty(); q.pop())
{
auto& str = q.front();
// TODO: do something with str.
}
【讨论】:
&?
std::queue::front() 返回对元素的引用,这就是& 的原因。我们通常不需要对象副本,我们可以就地操作字符串,因为我们稍后会弹出它。
最好使用while循环:
while (!q.empty()) {
// do operations.
}
但如果您在声明队列后立即执行此操作,您将不会进入循环,因为队列在创建时将为空。在这种情况下,您可以使用 do-while 循环:
queue<string> q;
do {
// enqueue and dequeue here.
}while (!q.empty());
【讨论】:
while ( ! q.empty() )
{
}
【讨论】:
是的,这是可能的。
int size=q.size();
for(int i=0;i<size;i++){
std::cout<<"\nCell - "<< q.front();
q.pop();
}
但人们大多避免使用 for 循环,因为每次队列的大小都会根据循环计数器检查,在 n/2 元素的中间弹出迭代将突然结束,因为大小将变为 n/2 而 i 是也n/2。下面提到的例子。
for(int i=0;i<q.size();i++){
std::cout<<"\nCell - "<< q.front();
std::cout<<"\tSize: - "<< q.size()<<" I value:"<<i;
q.pop();
}
【讨论】: