问答详情
源自:5-1 队列的实际应用

求大佬帮助

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
class Customer
{
public:
    Customer(string name,int age);
    Customer();
    void printInfo()const;
private:
    string m_strName;
    int m_iAge;
};
Customer::Customer(string name, int age)
{
 m_strName = name;
 m_iAge = age;
}
Customer::Customer()
{
    m_strName = "null";
    m_iAge = 0;
}
void Customer::printInfo()const
{
    cout<<m_strName<<" : "<<m_iAge<<endl;
}

class Queue
{
private:
    Customer* m_pQueue;          //队列数组指针
    int m_iQueueLen;           //队列数组长度
    int m_iQueueCapacity;      //队列数组容量
    int m_iHead;
    int m_iTail;

public:
    Queue(int queueCapacity)//创建队列
    {
        m_pQueue = new Customer[m_iQueueCapacity];
        ClearQueue();
        m_iQueueCapacity = queueCapacity;

    }
    virtual ~Queue()          //销毁队列
    {
        delete []m_pQueue;
        m_pQueue = NULL;
    }
    void ClearQueue()         //清空队列
    {
        m_iHead = 0;
        m_iTail = 0;
        m_iQueueLen = 0;
    }
    bool QueueEmpty() const   //判空队列
    {
        if(m_iQueueLen == 0){
            return true;
        }
        else return false;
    }
    bool QueueFull() const    //判断是否为满
    {
        if(m_iQueueLen == m_iQueueCapacity){
            return true;
        }
        else return false;
    }
    int QueueLength() const   //队列长度
    {
        return m_iQueueLen;
    }
    bool EnQueue(Customer element) //新元素入列
    {
        if(QueueFull())
        {
            return false;
        }
        else
        {
            m_pQueue[m_iTail] = element;
            m_iTail++;
            m_iQueueLen++;
            m_iTail = m_iTail % m_iQueueCapacity;
            return true;
        }
    }
    bool DeQueue(Customer &element)//首元素出列
    {
        if(QueueEmpty())
        {
            return false;
        }
        else
        {
            element = m_pQueue[m_iHead];
            m_iHead++;
            m_iQueueLen--;
            return true;
        }
    }
    void QueueTraverse()      //遍历队列
    {
        for(int i = m_iHead;i < m_iQueueLen + m_iHead;i++)
        {
            cout << "前面还有" << (i-m_iHead) << "个人" <<endl;
            m_pQueue[i % m_iQueueCapacity].printInfo();
        }
    }

};
int main()
{
    Queue *p = new Queue(4);
    Customer c1("Letme",1);
    Customer c2("Uzi",2);
    Customer c3("Ming",3);
    Customer c4("Mlxg",4);
    p->EnQueue(c1);
    cout<<"?"<<endl;
    p->EnQueue(c2);
    p->EnQueue(c3);
    p->EnQueue(c4);
    p->QueueTraverse();
    return 0;
}


这段代码的遍历和其他都没问题,但是往里面加数据时无法成功加入


提问者:UraNus0205 2018-09-21 17:09

个回答

  • 董大虾
    2018-10-06 17:15:38

    我也看了半天,发现问题出在这里,

      Queue(int queueCapacity)//创建队列
        {
            m_pQueue = new Customer[m_iQueueCapacity];//这里的m_iQueueCapacity并没有初始值,无法分配数组,应该是笔误,应该改成queueCapacity
            ClearQueue();
            m_iQueueCapacity = queueCapacity;

        }