zl程序教程

您现在的位置是:首页 >  其它

当前栏目

按条件替换-------replace_if

条件 替换 if replace -------
2023-09-14 09:13:38 时间

在这里插入图片描述
内置数据类型:

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//函数对象
class GREATERthan {
public:
	bool operator()(int val)
	{
		if (val > 5)
			return true;
			//如果这里的false不写,那么默认返回true
		return false;
	}

};
//普通函数
void print(int val)
{
	cout << val + 1 << " ";
}
void test01()
{
	vector<int> v = { 1,2,3,4,5,6,7,8,9 };
	replace_if(v.begin(), v.end(), GREATERthan(), 520);
	for_each(v.begin(), v.end(), print);
}
int main()
{

	test01();
	cout << endl;
	system("pause");
	return 0;
}

在这里插入图片描述

自定义数据类型:

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
//replace_if
//自定义数据类型
class person {
public:
	person(string name,int age):name(name),age(age){}
	int age;
	string name;
	//因为重载的==是为了让底层代码识别,所以依据底层代码写的规范,加上const,防止修改数据
	bool operator==(const person& p1)
	{
		if (p1.name == this->name && p1.age == this->age)
			return true;
		return false;
	}
};
//函数对象
class p {
public:
	void operator()(person& p1)
	{
		cout << p1.name << "\t" << p1.age << endl;
	}
};
//普通函数
bool a(person& p1)
{
	if (p1.age > 19)
		return true;
	return false;
}
//函数对象
class a1 {
public:
	bool operator()(person& p1)
	{
		if (p1.age > 19)
			return true;
		return false;
	}
};
void test01()
{
	person p1("孙悟空1", 18);
	person p2("孙悟空2", 19);
	person p3("孙悟空3", 20);
	person p4("猪八戒", 20);
	vector<person> v = { p1,p2,p3};
	cout << "替换前:\n";
	for_each(v.begin(), v.end(), p());
	//因为要查找与p1值相符的元素,所以涉及到了比较,如果是自定义数据类型,要重载==,返回值为bool
	//replace_if(v.begin(), v.end(), a1(), p4);
	replace_if(v.begin(), v.end(), a, p4);
	cout << "\n替换后: \n";
	for_each(v.begin(), v.end(), p());
}
int main()
{

	test01();
	cout << endl;
	system("pause");
	return 0;
}

在这里插入图片描述