【问题标题】:c++ pass two integers into queuec ++将两个整数传递到队列中
【发布时间】:2017-06-04 17:10:54
【问题描述】:

我使用数组创建了一个队列类,它最多必须包含两个整数。但是我如何一次将两个整数传递给数组?使用 bool Queue::enqueue(int, int)

我还需要一个 dequeue() 来打印两个整数并将它们从队列中丢弃。有什么建议如何做到这一点?

class Queue {
private:
  int * table;
  int front;
  int length;
  const int size=2;
public:
  Queue(int n);
  ~Queue();
  bool isEmpty();
  bool enqueue(int, int);
  bool dequeue();
  void print();
};

Queue::Queue(int n){
n=size;
length=0;
front=0;
table=new int[n];
}

Queue::~Queue(){
delete [] table;
}

bool Queue::isEmpty(){
if(length==size)
    return false;
else
    return true;
}

bool Queue::enqueue(int , int){
if (length == size)
  return -1; // Error, Queue is full
now i need to pass two integers if it it empty

【问题讨论】:

  • 你会如何用一个 int 来做呢?
  • 使您的队列通用并使用std::pair<int,int>?

标签: c++ queue


【解决方案1】:

为什么要使用队列的定义?好像你的设计有缺陷。但是我仍然使用向量编写了一个工作代码,它将解决您的目的(尽管我怀疑您想通过在入队/出队操作中添加/删除 2 个项目来实现什么)

#include <iostream>
#include <vector>

using namespace std;

class Queue {

  vector<int> table;
  const int CAPACITY = 2;

public:
  bool isEmpty();
  bool enqueue(int, int);
  void dequeue();
  void print();
};

bool Queue::isEmpty(){
    if(table.size())
        return false;
    else
        return true;
}

bool Queue::enqueue(int a, int b){
    if (table.size())
        return false; // Error, Queue is full
    table.push_back(a);
    table.push_back(b);
    return true;
}

void Queue::dequeue(){
    if(!table.size())
        return; //queue is empty
    table.pop_back();
    table.pop_back();
}

void Queue::print(){
    if(!table.size()){
        cout << "Queue is empty" << endl;
        return;
    }
    cout << table[0] << "," << table[1] << endl;
}

int main()
{
    //Make a variable of our container
    Queue queue;
    queue.enqueue(1,2);
    queue.print();
    queue.dequeue();
    queue.print();
    return 0;
}

【讨论】:

  • 假设这可能是一个家庭作业问题,我认为这个人的导师不会喜欢向量作为创建队列的内部数据结构。如果允许使用标准库,为什么不直接使用std::queuestd::dequeue
  • 好吧,在那种情况下,我认为我帮助了一项不道德的活动。家庭作业应该由学生自己完成,无需外部帮助;-)
  • 对于这种情况,最好不要自己回答问题,而是鼓励学生自己找出解决方案。不要只是发布代码,也许可以让人们知道人们可以做些什么来解决问题。
猜你喜欢
  • 2014-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 2019-10-04
  • 2014-12-06
  • 1970-01-01
  • 2014-08-10
相关资源
最近更新 更多