STL算法 -------- 删除算法1

1. remove()

2. remove_if()

注意:

        1.并不是真正的删除,而是把后面的元素向前移动,覆盖被删除元素

        2.返回新的逻辑终点

#include <iostream>
#include <algorithm>
#include <list>
#include <vector>

using namespace std;

template <typename T>
void Print( const T& t )
{
	for(typename T::const_iterator itr=t.begin(); itr!=t.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;
}

int main()
{
	list<int> lst;
	
	for(int i=1; i<=6; ++i)
	{
		lst.push_front(i);
		lst.push_back(i);
	}
	Print(lst);

	list<int>::iterator end;
	end = remove( lst.begin(), lst.end(), 3 );
	for(list<int>::const_iterator itr=lst.begin(); itr!=end; ++itr )
	{
		cout<<*itr<<' ';
	}cout<<endl;
	cout<<"erase total "<<distance(end, lst.end())<<" num 3"<<endl;
	
	//真正删除
	lst.erase(end, lst.end());
	Print(lst);

	vector<int> vec;
	for( int i=2; i<=6; ++i )
	{
		vec.push_back(i);
	}
	for( int i=4; i<=9; ++i )
	{
		vec.push_back(i);
	}
	for( int i=1; i<=7; ++i )
	{
		vec.push_back(i);
	}
	Print(vec);
	vec.erase(remove(vec.begin(), vec.end(), 5), vec.end());
	Print(vec);

	vec.erase(remove_if(vec.begin(), vec.end(),
					bind2nd(less<int>(), 4)), vec.end());
	Print(vec);
	

	return 0;
}


posted @ 2015-03-09 18:09  SandKing  阅读(4)  评论(0)    收藏  举报  来源