使用For循环将队列排入队列并使其出列 - C ++

时间:2016-04-30 04:41:35

标签: c++ arrays loops queue

我正在编写一个涉及队列的课程,而且我仍然坚持使用可能不是用户输入的项目的入队和出队(队列的类模板中的布尔函数)的概念,例如作为文件中的数字。我已经尝试运行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 . . .

我想知道我是不是正确地做了什么,或者是否有不同的方式来排队某些物品。非常感谢任何帮助或提示。

1 个答案:

答案 0 :(得分:2)

只要while(intQueue.enqueue(i))返回评估为intQueue.enqueue(i))的值,

true就会继续执行。

您需要使用的是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";
   }
}
相关问题