STL中vector,list,deque,set,map都有erase操作,但是其操作有较大的不同。
int main() //stl的erase操作 { int tmp; vector<int> v; list<int> l; deque<int> d; set<int> s; map<int, int> m; for (int i = 0; i < 10; i++) { v.push_back(i); l.push_back(i); d.push_back(i); s.insert(i); m.insert(make_pair(i, i)); } //vector 去偶数,只能erase返回下一个iterator给itv,否则wrong vector<int>::iterator itv; for (itv = v.begin(); itv != v.end();) { if (*itv % 2 == 0) itv = v.erase(itv); else itv++; } for (itv = v.begin(); itv != v.end();) { if (*itv % 3 == 0) itv = v.erase(itv); else itv++; } cout << "vector:"; for (itv = v.begin(); itv != v.end(); itv++){ cout << *(itv) << " "; } cout << endl; //list 去偶数,其iterator可以使用,erase后itl++方式,也可以使用返回itl方式 list<int>::iterator itl; for (itl = l.begin(); itl != l.end();) { if (*itl % 2 == 0) l.erase(itl++); else itl++; } for (itl = l.begin(); itl != l.end();) { if (*itl % 3 == 0) itl = l.erase(itl); else itl++; } cout << "List:"; for (itl = l.begin(); itl != l.end(); itl++){ cout << *(itl) << " "; } //deque 去除偶数 ,和vector类似,只能使用返回itd方式 deque<int>::iterator itd; for (itd = d.begin(); itd != d.end();) { if (*itd % 2 == 0) itd = d.erase(itd); else itd++; } cout << endl; cout << "deque:"; for (itd = d.begin(); itd != d.end(); itd++) { cout << *(itd) << " "; } cout << endl; //set 去除偶数 ,和list类似,可以使用erase后its++方式,也可以使用返回its方式 set<int>::iterator its; for (its = s.begin(); its != s.end();) { if (*its % 2 == 0) s.erase(its++); else its++; } for (its = s.begin(); its != s.end();) { if (*its % 3 == 0) its = s.erase(its); else its++; } cout << "set:"; for (its = s.begin(); its != s.end(); its++) { cout << *(its) << " "; } cout << endl; //map 去除偶数 ,类似list,可以使用erase后itm++方式,也可以使用返回itm方式 map<int, int>::iterator itm; for (itm = m.begin(); itm != m.end();) { if ((*itm).first % 2 == 0) m.erase(itm++); else itm++; } for (itm = m.begin(); itm != m.end();) { if ((*itm).first % 3 == 0) itm = m.erase(itm); else itm++; } cout << "map:"; for (itm = m.begin(); itm != m.end(); itm++) { pair<int, int> tmp = *(itm); cout << tmp.first<< "-"<<tmp.second<<" "; } cout << endl; return 0; }
输出结果