【5、STL 常用算法】

5、STL 常用算法

1、概述:

  • 算法主要是由头文件,,组成
  • algorithm 是所有STL头文件中最大的一个,范围涉及到比较、交换、查找、遍历操作,复制、修改等等
  • numeric体积很小,只包括几个在序列上面进行简单数学运算的模板函数
  • functional定义了一些模板类,用以声明函数对象
    5.1常用遍历算法
    1、学习目标:
  • 掌握常用的遍历算法

2、算法简介;

  • for_each //遍历容器
  • transform //搬运容器到另一容器中

5.1.1 for_each

1、学习目标:

  • 实现遍历容器

2、函数原型:

  • for_each(iterator beg,iterator end,_func);
  • //遍历算法 遍历容器元素
  • //beg开始迭代器
  • //end结束迭代器
  • //_func函数或者函数对象

3、代码

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
void Prtin01(int val)
{
	cout << val << " ";
}

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

void test01()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}

	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;

	for_each(v.begin(), v.end(), Prtin01);
	cout << endl;

	for_each(v.begin(), v.end(), Print02());
	cout << endl;
}

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

4、总结:

  • for_each在实际开发中最常用的遍历算法,需要熟练掌握

5、运行结果
在这里插入图片描述

5.1.2 transform

1、功能描述:

  • 搬运容器到另一个容器中

2、 函数原型:

  • transfrom(iterator beg1,iterator end1,iterator beg2,_func);
  • //beg1原容器开始迭代器
  • //end1原容器结束迭代器
  • //beg2目标容器开始迭代器
  • //_func函数或者函数对象

3、代码

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
class Transform
{
public:
	int operator()(int v1)
	{
		return v1 ;
	}
};

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

void test01()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	vector<int>vTarget;// 目标容器
	vTarget.resize(v.size());//目标容器 需要提前开辟空间

	transform(v.begin(), v.end(), vTarget.begin(), Transform());

	for_each(vTarget.begin(), vTarget.end(), MyPrint());
	cout << endl;
}

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

4、总结:

  • 搬运的目标容器必须要提前开辟空间,否则无法正常搬运

5、运行结果
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值