【C++】常用拷贝算法和替换算法

【C++】常用拷贝算法和替换算法_第1张图片
【C++】常用拷贝算法和替换算法_第2张图片

#include
using namespace std;
#include
#include
//常用拷贝和替换算法copy

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

void test01()
{
	vector<int>v1;
	for (int i = 0; i < 10; 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(), myPrint);
	cout << endl;

}

int main() {
	test01();
	system("pause");

	return 0;
}
//总结:利用copy算法在拷贝时,目标容器记得提前开辟空间

【C++】常用拷贝算法和替换算法_第3张图片

#include
using namespace std;
#include
#include
//常用拷贝和替换算法replace

class MyPrint
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};

void test01()
{
	vector<int>v;
	v.push_back(20);
	v.push_back(30);
	v.push_back(50);
	v.push_back(30);
	v.push_back(40);
	v.push_back(20);
	v.push_back(10);
	v.push_back(20);

	cout << "替换前:" << endl;
	for_each(v.begin(), v.end(), MyPrint());
	cout << endl;

	//将20替换成2000
	replace(v.begin(), v.end(), 20, 2000);
	cout << "替换后:" << endl;
	for_each(v.begin(), v.end(), MyPrint());
	cout << endl;
}

int main() {
	test01();
	system("pause");

	return 0;
}

【C++】常用拷贝算法和替换算法_第4张图片

#include
using namespace std;
#include
#include

class MyPrint
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};

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

//常用拷贝和替换算法 replace_if
void test01()
{
	vector<int>v;
	v.push_back(10);
	v.push_back(40);
	v.push_back(20);
	v.push_back(40);
	v.push_back(30);
	v.push_back(50);
	v.push_back(20);
	v.push_back(30);

	cout << "替换前:" << endl;
	for_each(v.begin(), v.end(), MyPrint());
	cout << endl;

	//将大于等于30 替换为 3000
	replace_if(v.begin(), v.end(), Greater30(), 3000);
	cout << "替换后:" << endl;
	for_each(v.begin(), v.end(), MyPrint());
	cout << endl;
}

int main() {
	test01();
	system("pause");

	return 0;
}
//replace_if按条件查找,可以利用仿函数灵活筛选满足的条件

【C++】常用拷贝算法和替换算法_第5张图片

#include
using namespace std;
#include
#include
//常用拷贝和替换算法swap

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

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

	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
		v2.push_back(i + 100);
	}

	cout << "交换前:" << endl;
	for_each(v1.begin(), v1.end(), myPrint);
	cout << endl;
	for_each(v2.begin(), v2.end(), myPrint);
	cout << endl; 

	cout << "--------------------" << endl;
	cout << "交换后:" << endl;
	swap(v1, v2);
	for_each(v1.begin(), v1.end(), myPrint);
	cout << endl;
	for_each(v2.begin(), v2.end(), myPrint);
	cout << endl;
}

int main() {
	test01();
	system("pause");

	return 0;
}
//总结:swap交换容器时,注意交换的容器要同种类型

你可能感兴趣的:(c++,算法,开发语言)