将数据从一个队列移动到另一个队列
问题描述:
我将队列出队,并且员工的薪水低于50,000。我不知道如何将它排入另一个队列,因为我的排队函数有三个参数。我的任务说创建一个班,然后在主要两个队列。我把队列作为班级的对象,这是正确的吗?如何排队进入第二个队列,只有一个入队函数需要三个参数。感谢所有的帮助。将数据从一个队列移动到另一个队列
#include <cstdlib>
#include <iostream>
#include <string>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::fixed;
using std::setprecision;
struct node{
string name;
int id;
int salary;
struct node *next;
};
node *rear;
node *front;
class DynEmpQueue{
private:
int counter = 0;
public:
void enqueue(string, int, int);
void dequeue();
void traverse()const;
DynEmpQueue()
{
rear = nullptr;
front = nullptr;
counter = 0;
}
};
void DynEmpQueue::enqueue(string localName, int localID, int localSalary)
{
node *temp;
temp = new (struct node);
temp -> name = localName;
temp -> id = localID;
temp -> salary = localSalary;
temp -> next = nullptr;
if (front == nullptr)
front = temp;
else
rear -> next = temp;
rear = temp;
counter++;
}
void DynEmpQueue::dequeue()
{
string localName;
int localID;
int localSalary;
node *temp;
if (front == nullptr)
cout << "The queue is empty.";
else
{
temp = front;
localName = temp -> name;
localID = temp -> id;
localSalary = temp -> salary;
front = front -> next;
delete temp;
counter--;
}
}
void DynEmpQueue::traverse()const
{
node *temp;
temp = front;
if (front == nullptr)
cout << "Queue is empty.";
else
{
cout << "Queue contains " << counter << " elements." << endl;
cout << "Queue elements:" << endl;
while (temp != nullptr)
{
cout << temp -> name << "\t" << temp -> id << "\t" << temp -> salary << endl;
temp = temp -> next;
}
}
}
int main()
{
const int NumberEmployees = 5;
DynEmpQueue originalQueue;
originalQueue.enqueue("Justin Gray", 100, 104000);
originalQueue.enqueue("Mike Smith", 200, 207000);
originalQueue.enqueue("Jose Cans", 400, 47000);
originalQueue.enqueue("Auston Matts", 300, 31000);
originalQueue.enqueue("Liz Learnerd", 600, 89100);
node object;
DynEmpQueue demandSalaryIncrease;
for (int i = 0; i < NumberEmployees; i++)
{
originalQueue.dequeue();
if (object.salary <= 50000)
demandSalaryIncrease.enqueue();
}
demandSalaryIncrease.traverse();
return 0;
}
答
您无法知道队列中存在哪些员工。看你如何定义你的方法:
void enqueue(string, int, int);
void dequeue();
void traverse() const;
正如你所看到的,没有方法将返回node
或员工的数据。所以,就像你现在宣布这个班级一样,没有办法从你的队列中获得员工。而且,由于你甚至无法让员工进入队列,所以你不能将他们添加到另一个队列中。
可能的解决方案:
修改您traverse()
方法,使得它需要一个工资作为参数,并返回包含所有员工的阵列(或甚至一个队列)的量,薪水比薪水低。
一个更好,更灵活的解决方案是使用谓词,但是(因为你使用的是全局变量),看起来好像你不是在寻找完美的解决方案。
让我感到震惊的是你有全局变量'front'和'rear'。为什么全局变量?我倾向于认为'front'和'rear'节点属于队列类的一个实例,而不是一个翻译单元。 –
我将它们作为全局变量,因为它们一直都是在课堂上设置的。我应该搜索每个出列的节点,以便查看他们的薪水是高于还是低于50,000? – hockey34
您的出队操作不必要地将结果拉入本地数据,然后丢弃它。如果你要从队列中取出某些东西,可能首先将它存储在某个地方。看起来你需要一个'front()'动作,以及一个'empty()'状态检查。 – WhozCraig