【问题标题】:Using a For Loop to Enqueue and Dequeue a Queue - C++使用 For 循环使队列入队和出队 - C++
【发布时间】:2016-04-30 04:41:35
【问题描述】:

我正在学习关于队列的课程,但对于可能不是用户输入的项目(例如文件。我尝试运行一个 for 循环,以便将某些项目排入队列,例如仅将偶数整数(来自列表 1-10)放入队列:

for(int i = 1; i <= 10; i++)
{
   if(i % 2 == 0)
      while(intQueue.enqueue(i))
          cout << i << " has been added to the queue . . .\n";
}

但由于某种原因,我只会在重复时将第一项添加到队列中:

2 has been added to the queue . . .
2 has been added to the queue . . .
2 has been added to the queue . . .
2 has been added to the queue . . .
2 has been added to the queue . . .

我想知道是不是我做的不对,或者是否有其他方法可以将某些项目排入队列。非常感谢任何帮助或提示。

【问题讨论】:

  • 删除while()

标签: c++ arrays loops queue


【解决方案1】:

只要intQueue.enqueue(i)) 返回的值等于truewhile(intQueue.enqueue(i)) 就会继续执行。

你需要使用的是if

for(int i = 1; i <= 10; i++)
{
   if (i % 2 == 0)
   {
      if (intQueue.enqueue(i))
          cout << i << " has been added to the queue . . .\n";
      else
          cout << i << " has not been added to the queue . . .\n";
   }
}

【讨论】:

  • @JosiahHolmes,很高兴听到这个消息。
  • @JosiahHolmes - 如果有帮助,您应该接受答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 2013-07-07
相关资源
最近更新 更多