【问题标题】:In queue,after insertion and deletion , the deleted element also appears in Output.why?在队列中,插入和删除后,被删除的元素也会出现在输出中。为什么?
【发布时间】:2014-03-01 16:05:39
【问题描述】:
#include<iostream>
#include<string.h>

using namespace std;    

class queue  
{
int f,r;
int a[5];

public:

 queue()
 {
    f=r=-1;
 }

在数组中插入元素

   void enqueu(int n)  

  {
    if(r==4)
        cout<<"Overflow"<<endl;
     else
     {
        r++;
     a[r]=n;
     }
   if(f==-1)
        f=0;
   }

从数组中删除元素

 void dequeu() 
       {
     if(f==-1)
        cout<<"Underflow"<<endl;

        else if(f==4)
        f=-1;

       else
      {
        cout<<"The Deleted Element is "<<a[f]<<endl;
        f++;
        }
  }

当我尝试显示 Array 的元素时,我删除的元素也会出现。

   void show()  
  // showing array elements
  {
    for(int i=0;i<5;i++)
        cout<<a[i]<<endl;
  }

 };

int main()

 {
  queue obj;

  int n,num;

我在这里使用 do while 会不断询问是插入还是删除。

   do   
   {
   cout<<"1: Insert Element In Queue"<<" 2: Delete Element "<<" 3:Press 0 to Exit<<endl;

    cin>>n;

  switch(n)  
   {
  case 1:
    {
        cout<<"Enter Element to insert"<<endl;
        cin>>num;
        obj.enqueu(num);
    break;
    }
  case 2:
    {
        obj.dequeu();
        break;
    }
  }
  }
 while(n!=0);

 obj.show();


 return 0;
  }

【问题讨论】:

  • 另外,在dequeu() 中,如果f==r,删除元素并将fr 都更改为-1
  • 为什么你的缩进如此时髦?

标签: c++ class queue


【解决方案1】:

enqueu()dequeu() 看起来好像容器中有多少元素是由成员 fr 确定的。但是您的 show() 会忽略它们,只打印所有五个数组元素。

【讨论】:

    【解决方案2】:

    dequeueshow 这两个函数都是错误的。

    当你删除一个元素时,你应该左移所有剩余的元素。

    所以在 dequeue 中 f 永远不能等于 4。它要么等于 -1 要么等于 0。所以我将按照以下方式重写函数:

     void dequeu()
     {
         if ( r == -1 )
         {
            cout<<"Underflow"<<endl;
         }
         else
         {
            cout << "The Deleted Element is " << a[f] << endl;
            for ( int i = f; i < r; i++ ) a[i] = a[i+1]; 
            if ( --r == -1 ) f = r;
         }
      }
    

    函数显示应该只输出队列中的实际元素

       void show() const  
      // showing array elements
      {
        for ( int i = f; i < r + 1; i++ ) cout << a[i] << endl;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 2013-08-27
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多