替换算法-----replace

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

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//replace
//内置数据类型
class p {
    
    
public:
	void operator()(int val)
	{
    
    
		cout << val << " ";
	}
};
void test01()
{
    
    
	vector<int> v = {
    
     4,7,2,7,8,7,9,7,10 };
	cout << "替换前:";
	for_each(v.begin(), v.end(), p());
	cout << "\n替换后: ";
	replace(v.begin(), v.end(), 7, 520);
	for_each(v.begin(), v.end(), p());
	
}
int main()
{
    
    

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

在这里插入图片描述
自定义数据类型
注意点:因为要查找与p1值相符的元素,所以涉及到了比较,如果是自定义数据类型,要重载==,返回值为bool

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
//replace
//自定义数据类型
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;
	}
};
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(v.begin(), v.end(), p1, p4);
	cout << "\n替换后: \n";
	for_each(v.begin(), v.end(), p());
}
int main()
{
    
    

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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_53157173/article/details/113914200