stl实现插入排序的问题
template <class T> void InsertSort(vector<T>& v) //插入排序{ vector<T> temp; typedef vector<T>::iterator VI; temp.push_back(v[0]); for (VI i = v.begin()+1;i<v.end();++i) { for (VI j = temp.end()-1;j>=temp.begin();--j) { if ((*i)>=(*j)) { temp.insert(j+1,(*i)); break; } if (j==temp.begin()&&(*i)<(*j)) { temp.insert(temp.begin(),(*i));//[color=#800000]问题应该在这里 但是不知道啥问题[/color] } } } v=temp;}if (j==temp.begin()&&(*i)<(*j)) { temp.insert(temp.begin(),(*i));//[color=#800000]问题应该在这里 但是不知道啥问题[/color]break;//在这里加个break就可以了 }
[解决办法]
如果你不在temp.insert(temp.begin(),(*i));这条语句后加break的话,执行完插入语句后,迭代器j就失效了,不再执向temp.begin()了,而程序会继续执行下一句,也就是下面这一句:
for (VI j = temp.end()-1;j>=temp.begin();--j);会继续对j进行--j;操作,然而当前迭代器j已经失效了,再对j进行前自减操作是非法的,会发生运行时错误,程序崩溃