簡體   English   中英

使用For循環使隊列入隊和出隊-C ++

[英]Using a For Loop to Enqueue and Dequeue a Queue - C++

我正在上一堂涉及隊列的課程,我停留在入隊和出隊(隊列類模板中的布爾函數)的概念,這些項可能不是用戶輸入的,例如文件中的數字。 我試過運行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(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";
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM