C++进阶STL-常用的拷贝和替换算法

copy

  • OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)

例子:将v1的第二个元素开始到最后一个元素,拷贝给v2


#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;



void Print(int n)
{
	cout << " " << n;
}
int main()
{
	vector<int> v1;
	for (int i = 0; i < 5; i++)
	{
		v1.push_back(i);
	}
	cout << "v1 : ";
	for_each(v1.begin(), v1.end(), Print); cout << endl;

	vector<int>v2;
	v2.resize(v1.size()-1);

	cout << "v2 : ";
	copy(v1.begin()+1,v1.end(),v2.begin());
	for_each(v2.begin(), v2.end(), Print); cout << endl;
	
    return 0;
}


在这里插入图片描述




swap

  • void swap (T& a, T& b)
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <time.h>
using namespace std;


void Print(int n)
{
	cout << " " << n;
}
int main()
{
	srand((unsigned int) time(NULL));
	vector<int> v1;
	for (int i = 0; i < 5; i++)
	{
		v1.push_back(rand()%10);
	}

	vector<int>v2;
	for (int i = 0; i < 4; i++)
	{
		v2.push_back(rand() % 10);
	}

	cout << "v1 : ";
	for_each(v1.begin(), v1.end(), Print); cout << endl;
	cout << "v2 : ";
	for_each(v2.begin(), v2.end(), Print); cout << endl;

	swap(v1, v2);
	cout << "----------------------------------------------------" << endl;//交换后

	cout << "v1 : ";
	for_each(v1.begin(), v1.end(), Print); cout << endl;
	cout << "v2 : ";
	for_each(v2.begin(), v2.end(), Print); cout << endl;
    return 0;
}


结果:
在这里插入图片描述




replace

  • void replace (ForwardIterator first, ForwardIterator last,
    const T& old_value, const T& new_value)
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <time.h>
using namespace std;


void Print(int n)
{
	cout << " " << n;
}
int main()
{
	srand((unsigned int) time(NULL));
	
	vector<int> v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(rand()%10);
	}



	cout << "v1 : ";
	for_each(v1.begin(), v1.end(), Print); cout << endl;

	replace(v1.begin(),v1.end(), 0,100);
	cout << "---------替换后----------" << endl;

	cout << "v1 : ";
	for_each(v1.begin(), v1.end(), Print); cout << endl;

    return 0;
}


结果:所有0,替换成100,如果没有0就不进行替换
在这里插入图片描述




replace_if

  • void replace_if (ForwardIterator first, ForwardIterator last,
    UnaryPredicate pred, const T& new_value)
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <time.h>
using namespace std;


void Print(int n)
{
	cout << " " << n;
}
 bool Compare(int n) 
{
		return n > 5;
}

int main()
{
	vector<int> v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}

	cout << "v1 : ";
	for_each(v1.begin(), v1.end(), Print); cout << endl;

	replace_if(v1.begin(),v1.end(), Compare ,100); //如果Compare返回true 就替换成100
	cout << "---------替换后----------" << endl;

	cout << "v1 : ";
	for_each(v1.begin(), v1.end(), Print); cout << endl;

    return 0;
}


结果:
在这里插入图片描述




猜你喜欢

转载自blog.csdn.net/zzyczzyc/article/details/83028322