removeAt()是不安全的,最安全的是erase(),如果用removeOne()还要重载运算符 == ,不爽,测试用例如下:
typedef struct _IntStruct_t{
int a;
int b;
float c;
bool operator ==(const _IntStruct_t &a){
return (a.c == this->c);
}
}IntStruct_t;
QDebug operator<<(QDebug dbg, const IntStruct_t &message)
{
dbg << message.a << message.b << message.c;
return dbg.maybeSpace();
} QList<IntStruct_t> iList,iListBack;
iList.append({0,0,0});
iList.append({1,1,1});
iList.append({2,2,2});
iList.append({3,3,2});
iList.append({4,4,3});
iList.append({5,5,6});
iList.append({6,5,5});
iList.append({7,6,6});
iList.append({8,7,2});
iListBack = iList;
for(int i=0;i<iList.size();i++)
if(iList.value(i).c == 2){
qDebug() <<"i="<<i<<",size="<<iList.size();
iList.removeAt(i);
qDebug() <<"After size="<<iList.size();
}
qDebug() <<"使用for错误:"<<iList;
iList = iListBack;
for(auto &i:iList){
if(i.c == 2)
iList.removeOne(i);
}
qDebug() <<"使用遍历结果:"<<iList;
iList = iListBack;
for(auto i=iList.begin();i!=iList.end();){
if((*i).c == 2)
i = iList.erase(i);
else
++i;
}
qDebug() <<"使用迭代器结果:"<<iList;
iList = iListBack;
QListIterator<IntStruct_t> it(iList);
while(it.hasNext()){
auto value = it.next();
if(value.c == 2)
iList.removeOne(value);
}
qDebug() <<"使用Java迭代器结果:"<<iList;
iList.clear();
iList.append(iListBack);
qDebug() <<"复制后的结果:"<<iList;运行后输出:
i= 2 ,size= 9 After size= 8 i= 7 ,size= 8 After size= 7 使用for错误: (000, 111, 332, 443, 556, 655, 766) 使用遍历结果: (000, 111, 443, 556, 655, 766) 使用迭代器结果: (000, 111, 443, 556, 655, 766) 使用Java迭代器结果: (000, 111, 443, 556, 655, 766) 复制后的结果: (000, 111, 222, 332, 443, 556, 655, 766, 872)
在有重复元素情况下,for+removeAt明显错误,删除不干净。
空名网友:for+removeAt因为你删完i没减一把移动到前面的元素跳过去了,根本不是元素重复的问题。
2022-12-11 19:19:59 回复