01 常用拷贝和替换算法_copy

02 常用拷贝和替换算法_replace

03 常用拷贝和替换算法_replace_if

04 常用拷贝和替换算法_swap


01 常用拷贝和替换算法_copy

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//复制拷贝
void print(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}

	for_each(v.begin(), v.end(), print);
	cout << endl;
	vector<int>v2;
	v2.resize(v.size());

	copy(v.begin(), v.end(), v2.begin());
	for_each(v2.begin(), v2.end(), print);
	cout << endl;

}

int main()
{
	test01();
	system("pause");
	return 0;
}
//总结:利用cpy算法是,目标容器记得提前开辟空间

02 常用拷贝和替换算法_replace

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

void print(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int>v;
	v.push_back(20);
	v.push_back(50);
	v.push_back(30);
	v.push_back(70);
	v.push_back(20);
	v.push_back(20);

	cout << "替换前" << endl;
	for_each(v.begin(), v.end(), print);
	cout << endl;
	cout << "替换后" << endl;
	replace(v.begin(), v.end(), 20, 10000);
	for_each(v.begin(), v.end(), print);
	cout << endl;

}

int main()
{
	test01();
	system("pause");
	return 0;
}

//总结:replace会替换区间内所以满足条件的元素

03 常用拷贝和替换算法_replace_if

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

//按条件查找,替换所有满足条件
class Print {
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};

class Greate30 {
public:
	bool operator()(int val)
	{
		return val > 30;
	}

};
void test01()
{
	vector<int> v;
	v.push_back(10);
	v.push_back(43);
	v.push_back(45);
	v.push_back(67);
	v.push_back(27);
	v.push_back(74);
	v.push_back(16);
	v.push_back(78);
	cout << "替换前" << endl;
	for_each(v.begin(), v.end(), Print());
	cout << endl;
	cout << "替换后" << endl;
	//将大于30的替换为4000
	replace_if(v.begin(), v.end(), Greate30(), 4000);
	for_each(v.begin(), v.end(), Print());
	cout << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

04 常用拷贝和替换算法_swap

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

//按条件查找,替换所有满足条件
class Print {
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};

void test01()
{
	vector<int> v;
	vector<int> v2;

	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
		v2.push_back(i + 1000);
	}
	cout << "交换前" << endl;
	for_each(v.begin(), v.end(), Print());
	cout << endl;
	for_each(v2.begin(), v2.end(), Print());
	cout << endl;

	cout << "交换后" << endl;
	swap(v, v2);
	for_each(v.begin(), v.end(), Print());
	cout << endl;
	for_each(v2.begin(), v2.end(), Print());
	cout << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

//总结:swap交换容器时,交换容器要是同等类型