Maison  >  Questions et réponses  >  le corps du texte

数据结构 - C++删除表中相同元素,循环问题在哪?

template <class T>
bool SeqList<T>::Delsame(T x)
{
    int i,j;
    for(int j=1;j<n+1;j++)
    {
        if (elements[j-1]==x)
        {
            for (int i=j-1;i<n;i++)
                {
                    elements[i]=elements[i+1];
                }
             n--;
        }
    }
    return true;
}

删除表中相同元素部分的代码,当表中所需删除元素只有1个的时候,运行正常.当所需删除元素有多个的时候,运行结果正确,但是会提示.exe已停止工作,所以想知道循环问题在哪??

ringa_leeringa_lee2715 Il y a quelques jours620

répondre à tous(2)je répondrai

  • ringa_lee

    ringa_lee2017-04-17 15:35:52

    n代表的是顺序表元素个数吗?如果是的话elements[i+1]这一句会取到elements[n]的,越界了。
    BTW,第一个循环为什么直接j++?如果删除了一个元素,后面的往前移了,还进行j++,那岂不是会跳过一个元素。
    你试一下两个相邻的相同元素能不能删除。

    répondre
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:35:52

    楼上已经指出了错误,我来尝试给出一个正确的实现

    int find(int lo,int hi,const T& e){
        while(lo<hi--&&elem[hi]!=e);
        return hi;//若失败返回lo-1
    }
    void remove(int lo,int hi){
        while(hi<size) elem[lo++]=elem[hi++];
    }
    void deduplication(){
        int i=1;
        while(i<size){
            (find(0,i,elem[i])<0)?
                i++:remove(i);
        }
    }

    répondre
    0
  • Annulerrépondre