C++常用拷贝和替换算法-replace_if()

C++常用拷贝和替换算法-replace_if()

功能描述:

  • 将区间内满足条件的元素,替换成指定元素
#include 
#include 
#include 
using namespace std;

class myPrint
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
class ReplaceGreater30
{
public:
	bool operator()(int val)
	{
		return val >= 30;
	}
};
void test01()
{
	vector<int> v;
	v.push_back(20);
	v.push_back(30);
	v.push_back(20);
	v.push_back(40);
	v.push_back(50);
	v.push_back(10);
	v.push_back(20);

	cout << "替换前: " << endl;
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;
	//将容器中大于等于30的替换成为3000
	cout << "替换后: " << endl;
	replace_if(v.begin(), v.end(), ReplaceGreater30(), 3000);
	for_each(v.begin(), v.end(), myPrint());
	cout << endl;
}
int main()
{
	test01();
	return 0;
}

你可能感兴趣的:(C++学习笔记,c++)