【发布时间】:2017-04-24 22:13:30
【问题描述】:
如果员工的工资低于 50,000,我将队列出队。我不确定如何将它排入另一个队列,因为我的入队函数需要三个参数。我的任务说要创建一个类,然后在 main 中创建两个队列。我将队列作为类的对象,这是正确的吗?我如何排入第二个队列,类中只有一个入队函数,该函数需要三个参数。感谢所有的帮助。
#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;
}
【问题讨论】:
-
让我印象深刻的是你有全局变量
front和rear。为什么是全局变量?我倾向于认为front和rear节点属于队列类的一个实例,而不是一个翻译单元。 -
我将它们作为全局变量,因为它们一直是在课堂上设置的。我应该搜索每个出队的节点,以便查看他们的薪水是高于还是低于 50,000?
-
您的出队操作不必要地将结果拉取存储到本地数据中,然后将其丢弃。如果你要从队列中取出一些东西,也许先把它存储在某个地方。看来您需要
front()操作以及empty()状态检查。 -
@hockey34 和
front和rear作为全局变量考虑当你构造demandSalaryIncrease和front = nullptr;执行时originalQueue的列表会发生什么。