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、运行结果