首页 > STL编程 > STL remove算法浅析

STL remove算法浅析

先来看一段英文的介绍。

      Remove removes from the range [first, last) all elements that are equal to value. That is, remove returns an iterator new_last such that the range [first, new_last) contains no elements equal to value.  The iterators in the range [new_last, last) are all still dereferenceable, but the elements that they point to are unspecified. Remove is stable, meaning that the relative order of elements that are not equal to value is unchanged.

      The meaning of "removal" is somewhat subtle. Remove does not destroy any iterators, and does not change the distance between first and last. (There's no way that it could do anything of the sort.) So, for example, if V is a vector, remove(V.begin(), V.end(), 0) does not change V.size(): V will contain just as many elements as it did before. Removereturns an iterator that points to the end of the resulting range after elements have been removed from it; it follows that the elements after that iterator are of no interest, and may be discarded. If you are removing elements from a Sequence, you may simply erase them. That is, a reasonable way of removing elements from a Sequence isS.erase(remove(S.begin(), S.end(), x), S.end()).

        简单的意思就是说,remove算法并不会真正删除容器中的元素。他的任务是负责把区间内的元素值为指定值的元素的位置腾出,然后后面的元素就会往前移动。返回一个新的end(),即为原来的区间移除指定值并且元素前移后的末尾的下一个位置。但是原来容器的end()并不会改变。

         比如说1 2 3 4 5 6 6 5 4 3 2 1这样的区间,如果移除值为3的元素,那么会变化为1 2 4 5 6 6 5 4 2 1 2 1。新的end指向后面那个2。容器的size不会因此而改变,新的end()迭代器由remove返回。

            remove的算法是稳定的,因为其他元素的相对位置并没有改变。如果要真正删除元素,那么要使用erase了。

#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
	list<int> coll;
	
	for(int i = 1; i <= 6; ++i)
	{
		coll.push_front(i);
		coll.push_back(i);
	}
	
	cout << "before remove:" << endl;
	copy(coll.begin(), coll.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	
	list<int> coll1(coll);
	remove(coll1.begin(), coll1.end(), 3);
	
	cout << "after remove:" << endl;
	copy(coll1.begin(), coll1.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	
	coll.erase(remove(coll.begin(), coll.end(), 3), coll.end());
	
	cout << "after remove and erase:" << endl;
	copy(coll.begin(), coll.end(), ostream_iterator<int>(cout, " "));
	cout << endl;

	return 0;
}

运行结果


觉得文章还不错?点击此处对作者进行打赏!


本文地址: 程序人生 >> STL remove算法浅析
作者:代码疯子(Wins0n) 本站内容如无声明均属原创,转载请保留作者信息与原文链接,谢谢!


更多



分类: STL编程 标签: , ,
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.