将字符串文字推入队列C ++

时间:2016-09-29 07:01:55

标签: c++ templates

我正在创建循环队列数据结构,并尝试将字符串元素传递到我的模板数组中:

 void testCircular()
{

   // create
   cout << "Create a string Queue with the default constructor\n";
   Queue <string> q(4); // create queue with a capacity of 4

   // instructions
   cout << "\tTo add the word \"dog\", type +dog\n";
   cout << "\tTo pop the word off the queue, type -\n";
   cout << "\tTo display the state of the queue, type *\n";
   cout << "\tTo quit, type !\n";

   // interact
   char instruction;
   string word;
   try
   {
      do
      {
         cout << "\t" << q << " > ";
         cin.ignore();
         cin  >> instruction;
         switch (instruction)
         { 
            case '+':
               cin >> word;

               //here is the problem
               q.push(word);
               break;
            case '-':
               q.pop();
               break;
            case '*':
               cout << "Size:     " << q.size()                   << endl;
               cout << "Empty?    " << (q.empty() ? "Yes" : "No") << endl;
               cout << "Capacity: " << q.capacity()               << endl;
               break;
            case '!':
               break;
            default:
               cout << "Invalid command\n";
         }            
      }
      while (instruction != '!');  

我的问题是当单词(即dog)被推入我的队列数组时,我收到一个seg错误错误,并带有以下消息:

Exception thrown at 0x59CC515F. Access violation writing location 0x5D77DCAF

这是我的推送方法:

template <class T>
void Queue <T>::push(const T & element)
{
    // if capacity is 0, allocate array
    if (_capacity == 0)
    {
        _capacity = 1;

        qArray = new T[_capacity];

        qArray[_back] = element;

        _numItems++;

        return;

    }
    //make sure the array is not full
    if (_numItems < _capacity)
    {

        if (_numItems != 0) // do not add onto back index for 1st insertion
        _back = (_back + 1) % _capacity;

        //push item onto queue
        qArray[_back] = element;

        _numItems++;
    }
    else
    {
        //double the array size
        realloc();
        push(element);
    }


}

我已经阅读了多篇帖子,但没有一篇特别解决这个问题。任何帮助将不胜感激。

0 个答案:

没有答案