导航

1.copy() //用于拷贝一个容器到另一个容器
2.replace() //将容器中的数进行替换
3.replace_if() //将容器中符合条件的数进行替换
4.swap() //将两个容器中数据进行互换

————————————————————————————————————————
1.copy()函数用法
copy(iterator beg,iterator end,iterator tar)
iterator beg:迭代器初始位置
iterator end:迭代器末尾位置
iterator tar:目标迭代器初始位置

注意:使用copy()之前要分配空间,resize()

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

void print(int val)
{
	cout<<val<<" ";
}

void test()
{
	//创建容器 
	vector<int> v1;
	for(int i=0;i<5;i++)
		v1.push_back(i);
	vector<int> v2;
	//拷贝之前要分配空间
	v2.resize(v1.size()); 
	//进行拷贝 
	copy(v1.begin(),v1.end(),v2.begin());
	for_each(v2.begin(),v2.end(),print); 
	 
}

int main()
{
	test();
	return 0;
} 

————————————————————————————————————————
2.replace() 函数使用
原型:replace(iterator beg,iterator end,oldval,newval)
iterator beg:迭代器初始位置
iterator end:迭代器末尾位置
oldval:容器中旧的数值
newval:将旧的数值改为新的数值

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

void print(int val)
{
	cout<<val<<" ";
}

void test()
{
	//创建容器 
	vector<int> v1;
	//插入数据 
	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(10);
	v1.push_back(10);
	
	cout<<"替换前:"<<endl;
	for_each(v1.begin(),v1.end(),print); 
	cout<<endl;
	
	//将容器中10替换为100 
	replace(v1.begin(),v1.end(),10,100);
	cout<<"替换后:"<<endl;
	for_each(v1.begin(),v1.end(),print); 
	 
}

int main()
{
	test();
	return 0;
} 

运行结果:
常用拷贝和替换算法  copy()   replace()  replace_if()  swap()_#include

————————————————————————————————————————
3.replace_if() 函数用法
原型:replace_if(iterator beg,iterator end,_pred,newvalue)
iterator beg:迭代器初始位置
iterator end:迭代器末尾位置
_pred:谓词,提供筛选要求
newvalue:替换后的新值

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

class print
{
public:
	void operator()(int val)  //写一个仿函数 
	{
		cout<<val<<" ";
	}
};

//写一个谓词,添加到replace_if中 
class Greater20
{
public:
	bool operator()(int val)
	{
		return val>20;      //判断是否大于20 
	}
};

void test()
{
	vector<int> v;
	v.push_back(10);
	v.push_back(20);
	v.push_back(50);
	v.push_back(15);
	v.push_back(60);
	v.push_back(40);
	
	cout<<"替换前:"<<endl;
	for_each(v.begin(),v.end(),print());
	cout<<endl;
	
	replace_if(v.begin(),v.end(),Greater20(),100);
	
	cout<<"替换后:"<<endl;
	for_each(v.begin(),v.end(),print());
	
}

int main()
{
	test();
	return 0;
}

作用:灵活的筛选数进行替换

————————————————————————————————————————

4.swap() 函数使用
原型:swap(v1,v2)
v1:容器1
v2:容器2

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

class print
{
public:
	void operator()(int val)  //写一个仿函数 
	{
		cout<<val<<" ";
	}
};

void test()
{
	vector<int> v;
	vector<int> v1;
	for(int i=0;i<10;i++){
		v.push_back(i);
		v1.push_back(i+5);
	}
		
	
	cout<<"替换前:"<<endl;
	for_each(v.begin(),v.end(),print());
	cout<<endl;
	for_each(v1.begin(),v1.end(),print());
	cout<<endl;
	
	swap(v,v1);    //将两个容器数据进行互换
	
	cout<<"替换后:"<<endl;
	for_each(v.begin(),v.end(),print());
	cout<<endl;
	for_each(v1.begin(),v1.end(),print());
	cout<<endl;
	
}

int main()
{
	test();
	return 0;
}