向容器中填充元素---fill

在这里插入图片描述
利用fill可以将容器区间填充为指定的值
属于算术生成算法一类的小型算法-----需要包含头文件numeric

自定义数据类型操作和内置数据类型一样

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
#include<numeric>
//自定义数据类型
class person {
    
    
public:
	person(string name, int age) :name(name), age(age) {
    
    }
	int age;
	string name;
	
};
//函数对象
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("猪八戒1", 21);
	person p5("猪八戒2", 22);
	vector<person> v = {
    
     p1,p2,p3,p4,p5 };
	//将容器中所有元素替换成p1
	fill(v.begin(), v.end(), p1);
	for_each(v.begin(), v.end(), p());
}
int main()
{
    
    

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

在这里插入图片描述

一般多用于后期填充

猜你喜欢

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