内置数据类型:
#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;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有