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

本文通过C++示例代码展示了STL中replace和replace_if函数的使用方法,包括如何替换列表中的元素及其条件变体,并演示了replace_copy及replace_copy_if函数的应用。

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;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值