STL - 移除(remove)和释放(erase)集合元素
remove(移除):
这个操作并不是真正地删除元素,它会移除指定的元素,然后后面的元素依次前移,最后用别的元素来补充。
erase(释放):
这个操作会指定释放区间的头和尾迭代器(iterator)。
如果要一次性删除指定元素:
coll.erase(remove(coll.begin(), coll.end(), [removed element]), coll.end());
代码如下:
list<int> coll1; for (int i = 1; i <= 6; ++i) { coll1.push_front(i); coll1.push_back(i); } cout << "** collection 1: **" << endl; ContainerUtil<list<int>>::printElements(coll1); // remove all elements with value 3 list<int>::iterator end = remove(coll1.begin(), coll1.end(), 3); cout << "** collection 1(after remove elements 3): **" << endl; ContainerUtil<list<int>>::printElements(coll1); // print number of removed elements cout << "number of removed elements : " << distance(end, coll1.end()) << endl; // release 'removed' elements coll1.erase(end, coll1.end()); cout << "** collection 1(after releasing removed elements): **" << endl; ContainerUtil<list<int>>::printElements(coll1); // remove & release elements with value 4 all at once coll1.erase(remove(coll1.begin(), coll1.end(), 4), coll1.end()); cout << "** collection 1(after remove & release elements 4): **" << endl; ContainerUtil<list<int>>::printElements(coll1);
运行结果:
** collection 1: **
6 5 4 3 2 1 1 2 3 4 5 6
** collection 1(after remove elements 3): **
6 5 4 2 1 1 2 4 5 6 5 6
number of removed elements : 2
** collection 1(after releasing removed elements): **
6 5 4 2 1 1 2 4 5 6
** collection 1(after remove & release elements 4): **
6 5 2 1 1 2 5 6
技术改变世界