如何在 c++ 中执行 for 循环直到队列为空

发布于 2024-09-26 14:25:00 字数 186 浏览 0 评论 0原文

我需要执行 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

花落人断肠 2024-10-03 14:25:00
while (!q.empty())
{
    std::string str = q.front();

    // TODO: do something with str.

    q.pop();
}
while (!q.empty())
{
    std::string str = q.front();

    // TODO: do something with str.

    q.pop();
}
始于初秋 2024-10-03 14:25:00

它与最佳答案的代码相同,但使用 for 循环。对我来说看起来更干净。

for (; !q.empty(); q.pop())
{
    auto& str = q.front();

    // TODO: do something with str.
}

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.
}
羁客 2024-10-03 14:25:00

最好使用 while 循环:

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

但是,如果您在声明队列后立即执行此操作,您将不会进入循环,因为队列在创建时将为空。在这种情况下,您可以使用 do-while 循环:

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

Its better to use a while loop as:

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

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:

queue<string> q;
do {
// enqueue and dequeue here.
}while (!q.empty());
浅沫记忆 2024-10-03 14:25:00
while ( ! q.empty() )
{
}
while ( ! q.empty() )
{
}
天暗了我发光 2024-10-03 14:25:00

是的,这是可能的。

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();
}

Yes its possible.

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

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.

for(int i=0;i<q.size();i++){
    std::cout<<"\nCell - "<< q.front();
    std::cout<<"\tSize: - "<< q.size()<<" I value:"<<i;
    q.pop();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文