stl::(14) Common copy and replacement algorithm

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>

using namespace std;

// copy算法 将容器被指定范围的元素拷贝到另一个容器中
// replace算法   将旧元素替换为新元素
// replace_if算法  按条件替换元素
// swap 算法    互换2个容器元素
class Compare {
    
    
public:
	bool operator()(int v) 
	{
    
    
		return v > 3;
	}
};

void copyReplaceVector()
{
    
    
	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());
	cout << "容器复制:";
	for_each(v2.begin(), v2.end(), [](int val) {
    
    cout << val << " "; });
	cout << endl;

	// 替换容器中的3,为300
	replace(v1.begin(), v1.end(), 3, 300);
	cout << "默认替换:";
	for_each(v1.begin(), v1.end(), [](int val) {
    
    cout << val << " "; });
	cout << endl;

	// 大于3的元素替换为33
	replace_if(v1.begin(), v1.end(), Compare(), 33);
	cout << "条件替换:";
	for_each(v1.begin(), v1.end(), [](int val) {
    
    cout << val << " "; });
	cout << endl;


	// swap 交两个容器元素
	vector<int> v3;
	vector<int> v4;
	for (int i = 0; i < 10; i++)
	{
    
    
		v3.push_back(i);
		v4.push_back(i + 100);
	}
	swap(v3,v4);
	cout << "v3的元素:";
	for_each(v3.begin(), v3.end(), [](int val) {
    
    cout << val << " "; });
	
}


int main()
{
    
    
	copyReplaceVector();

}

Guess you like

Origin blog.csdn.net/qq_40329851/article/details/114465072