2016-04-08 13 views
0

偶数または奇数を異なるスタックに実装しようとしています&キュー。ここに私のコードです:スタック&キューを使用して偶数と奇数を分離する

どのように私のスタックを表示することができます&キュー? どのキューで奇数または偶数で分けることができますか?

#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 :: stack']を反復処理することはできません。キュー '](http://en.cppreference.com/w/cpp/container/queue)を直接参照することができます。そのため、要素を削除せずに値を表示する方法はありません。 –

+0

2つのスタックと2つのキューを作成します。私はすべての偶数と奇数をスタックに追加したい。また、キューと同じものが必要です。 –

答えて

0

私がコメントしたように、私はあなたが2つのスタックと2つのキューを必要とすると仮定します。 Oddは奇数のスタックコンテナと奇数のキューコンテナに行きます。たとえ偶数のスタックコンテナと偶数のキューコンテナにも行きます。

これは動作するはずです:

#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フロントフロントバックなどを混乱させました。 –

+0

@GabrielValedonスタックについては、こちらをご覧ください:http://stackoverflow.com/questions/12631514/how-can-i-print-out stdstack-and-return-its-sizeの内容と.top()の代わりに.front()と同じテクニックを使用します。 –

関連する問題