STL算法 -------- 替换算法

1. replace( b, e, ov, nv )

2. replace_if( b, e, p, v )

3.replace_copy( b1, e1, b2, ov,  nv )

4.replace_copy_if(b1, e1, b2, p, v )

#include <iostream>
#include <algorithm>
#include <list>
#include <iterator>
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=2; i<8; ++i )
	{
		lst.insert(lst.end(), i);
	}
	for( int i=4; i<10; ++i )
	{
		lst.push_back(i);
	}

	Print(lst);
	replace(lst.begin(), lst.end(), 6, 42);
	Print(lst);

	replace_if(lst.begin(), lst.end(), bind2nd(less<int>(), 5), 0);
	Print(lst);

	list<int> lst2;
	for( int i=2; i<=6; ++i )
	{
		lst2.push_back(i);
	}
	for( int i=4; i<=9; ++i )
	{
		lst2.push_back(i);
	}
	Print(lst2);

	replace_copy(lst2.begin(), lst2.end(), ostream_iterator<int>(cout, " "), 5, 55);
	cout<<endl;

	replace_copy_if(lst2.begin(), lst2.end(), ostream_iterator<int>(cout, " "), 
			bind2nd(less<int>(), 5), 42);
	cout<<endl;

	replace_copy_if(lst2.begin(), lst2.end(), ostream_iterator<int>(cout, " "), 
			bind2nd(modulus<int>(), 2), 0);

	return 0;
}


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