C++使用堆栈和队列来分隔偶数和奇数
C++ using Stacks & Queues to separate even & odd numbers
我试图在不同的堆栈中实现偶数或奇数&队列。这是我的代码:
如何显示我的Stack&队列如何在任何队列中以奇数或偶数分隔?
#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 << "tt" << q2 << endl;
}
return 0;
}
正如我所评论的,我假设您想要两个堆栈和两个队列。奇数将转到奇数堆栈容器和奇数队列容器。Even将转到偶数堆栈容器和偶数队列容器。
这应该有效:
#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;
}
相关文章:
- boost::进程间消息队列引发错误
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 如何将 txt 文件中的行分隔为组件C++
- Android NDK传感器向事件队列报告奇怪的间隔
- 无法通过空白将文本文件行分隔为矢量
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 按对象的特定方法按升序排列的C++优先级队列
- 使用2个键的cpp-stl::优先级队列排序不正确
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 在一个读写器队列中,我可以用volatile替换原子吗
- 为什么我的多线程作业队列崩溃
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 使用"Task"函数指针队列定义作业管理器
- 在c++队列中使用pop和visit实现线程安全
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 打印优先级队列
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- C++使用堆栈和队列来分隔偶数和奇数