vector erase() 使用时遇到的问题及解决方法
iterator erase (const_iterator position);
//从vector中删除一个指定位置(position)元素,并返回删除元素的下一个迭代器
iterator erase (const_iterator first, const_iterator last);
//从vector中删除一个范围元素[first,last),不包括last,并返回last位置迭代器
常犯错误:
#include<iostream> #include<vector> using namespace std; int main(){ 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);//这种使用方法会内存错误,因为删除itor指定元素后,itor就变成野指针了,正确使用是itor重新赋值为erase返回值。 itor=array.erase(itor); } for (itor = array.begin(); itor != array.end(); itor++) { cout << *itor << " "; } }
//结果为:100 300 300 500
//原因:itor指向删除元素下一个元素后,itor++就跳过了删除元素的下一个元素
正确方法:
1.
#include<iostream> #include<vector> using namespace std; int main(){ 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 << " "; } }
//不太好 如果一开始就删的话--往哪减??? 所以第二个是最好的
2.
#include<iostream> #include<vector> using namespace std; int main(){ 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) array.erase(itor); else itor++; } for (itor = array.begin(); itor != array.end(); itor++) { cout << *itor << " "; } }