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_lee2017-04-17 15:35:52
Does n represent the number of elements in the sequence table? If so, the sentence elements[i+1]
would be taken as elements[n]
, which is out of bounds.
BTW, why is j++ used in the first loop? If an element is deleted, the following elements are moved forward, and j++ is executed, wouldn't an element be skipped?
Try to see if two adjacent identical elements can be deleted.
伊谢尔伦2017-04-17 15:35:52
The error has been pointed out upstairs, let me try to give a correct implementation
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);
}
}