vector::erase 从指定容器删除指定的元素
两个重载:
iterator erase (iterator position);
删除指定位置position的元素,并返回删除元素的下一个元素的迭代器
iterator erase (iterator first, iterator last);
删除从first到last(不包过last)之间的元素 [first,last),并返回last位置迭代器
遍历删除元素方法:
1.
vector<int>array; array.push_back(100); array.push_back(300); array.push_back(300); array.push_back(300); array.push_back(300); array.push_back(500); vector<int>::iterator itor; for (itor = array.begin(); itor != array.end(); itor++){ if (*itor == 300) array.erase(itor); } for (itor = array.begin(); itor != array.end(); itor++) { cout << *itor << " "; }
这种使用方法会内存错误,因为删除itor指定元素后,itor就编程野指针了,正确使用是itor重新赋值为erase返回值。
2.
vector<int>array; array.push_back(100); array.push_back(300); array.push_back(300); array.push_back(300); array.push_back(300); array.push_back(500); vector<int>::iterator itor; for (itor = array.begin(); itor != array.end(); itor++){ if (*itor == 300) itor=array.erase(itor); } for (itor = array.begin(); itor != array.end(); itor++) { cout << *itor << " "; }
这个方式在删除连续元素会错误,结果发现是100 300 300 500,因为itor指向删除元素下一个元素后,itor++就跳过了删除元素的下一个元素。
3.正确使用方式
vector<int>array; array.push_back(100); array.push_back(300); array.push_back(300); array.push_back(300); array.push_back(300); array.push_back(500); vector<int>::iterator itor; for (itor = array.begin(); itor != array.end(); ){ if (*itor == 300) itor=array.erase(itor); else itor++; } for (itor = array.begin(); itor != array.end(); itor++) { cout << *itor << " "; }