替换算法

<span style="font-family:SimSun;font-size:14px;font-weight: normal;">#include <iostream>
#include <algorithm>
#include <list>
#include <functional>
#include <iterator>

using namespace std;

int main()
{
	list<int> ilist;
	for (int i = 2; i <= 7; ++i)
		ilist.push_back(i);
	for (int i = 4; i <= 9; ++i)
		ilist.push_back(i);

	for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;
	cout << endl << endl;

	replace(ilist.begin(), ilist.end(), 6, 42);  // 将ilist数据中的所有的6替换成42,
	for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;
	replace_if(ilist.begin(), ilist.end(), bind2nd(less<int>(), 5), 0); //  bind2nd(less<int>(),5)是预定义的函数适配器,将小于5的数全部用0替换,
	for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;

	list<int> ilist2;
	for (int i = 2; i <= 6; ++i)
		ilist2.push_back(i);
	for (int i = 4; i <= 9; ++i)
		ilist2.push_back(i);

	for (list<int>::iterator iter = ilist2.begin(); iter != ilist2.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;

	replace_copy(ilist2.begin(), ilist2.end(), ostream_iterator<int>(cout, " "), 5, 90); 
	// ostream_iterator 输出流迭代器在iterator头文件中,将ilist2中的所有5替换成90,将其拷贝到cout中去,
	cout << endl;
	replace_copy_if(ilist2.begin(), ilist2.end(), ostream_iterator<int>(cout, " "), bind2nd(less<int>(), 5), 80);
	cout << endl;
	replace_copy_if(ilist2.begin(), ilist2.end(), ostream_iterator<int>(cout, " "), bind2nd(modulus<int>(), 2), 0);
	// (modulus<int>(), 2)是取模运算,将所有数除于2将所有的余数变成0,
	cout << endl;

	return 0;
}</span>


你可能感兴趣的:(替换算法)