2016-04-08 34 views
0

我試圖在不同的堆棧中實現偶數或奇數的隊列&隊列。這裏是我的代碼:使用堆棧和隊列來分隔偶數和奇數的C++

如何顯示我的堆棧&隊列? 如何在奇數或偶數隊列中分開?

#include <iostream> 
#include <stack> 
#include <queue> 
using namespace std; 

int main() 
{ 
stack <int> s1; 
queue <int> q1; 
int num[10]={0}; 

for(int i = 0; i < 10; i++) 
{ 
    cout << "Enter Number " << i << ": "; 
    cin >> num[i]; 

    s1.push(num[i]); 
} 

int s2; 
int q2; 
cout << "In Stack" << "\t" << "In Queue" << endl; 

while(!q1.empty()) 
{ 
    for(int i = 0; i <10; i++) 
    { 
     if(num[i]%2 == 0) 
     { 
      s2 = s1.top(); 
      s1.pop(); 
     } 
     else 
     { 
      q2 = q1.front(); 
      q1.pop(); 
     } 
    } 
    cout << s2 << "\t\t" << q2 << endl; 
} 

return 0; 
} 
+4

即使在棧和隊列奇!?目前還不清楚你試圖實現的目標 –

+2

你不能迭代['std :: stack'](http://en.cppreference.com/w/cpp/container/stack)或['std ::隊列'](http://en.cppreference.com/w/cpp/container/queue),所以沒有辦法顯示它們的值而不從它們中刪除元素。 –

+0

我創建了兩個堆棧和兩個隊列。我想在堆棧中添加所有的偶數和奇數。也希望與隊列相同。 –

回答

0

正如我所說,我假設你想要兩個堆棧和兩個隊列。奇數將進入一個奇數堆棧容器和一個奇數隊列容器。甚至會轉到一個偶數堆棧容器和一個偶數隊列容器。

這應該工作:

#include <stack> 
#include <queue> 

int main() 
{ 
    std::stack<int> MyOddStack; 
    std::queue<int> MyOddQueue; 

    std::stack<int> MyEvenStack; 
    std::queue<int> MyEvenQueue; 

    int MyNumbers[10]; 
    int InNum; 

    for (int i = 0; i < 10; i++) // take numbers from user and fill the container, the queue and the stack right away 
    { 
     std::cout << "Please enter number: " << std::endl; 
     std::cin >> InNum; 

     MyNumbers[i] = InNum; // put in the container 

     if (InNum % 2 == 0) // if even add to even queue and even stack 
     { 
      MyEvenQueue.push(InNum); 
      MyEvenStack.push(InNum); 
     } 
     else //else, add to odd queue and odd stack 
     { 
      MyOddQueue.push(InNum); 
      MyOddStack.push(InNum); 
     } 
    } 

    // You want to display any of the queues/stacks? 
    // put a for loop 
    // use .top() and/or .front() to display 
    // use .pop() everytime you display an element so you see the next element 

    return 0; 

} 
+0

是的,我想展示它,但我怎麼做呢?我有一個想法,但我困惑.pop .front .front .back等... –

+0

@GabrielValedon對於堆棧:請參閱這裏http://stackoverflow.com/questions/12631514/how-can-i-print-out - stdstack-and-return-its-size的內容,並使用相同的技術,但.front()而不是.top() –