2016-04-08 175 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() –