常 用 遍 历 算 法 常用遍历算法 常用遍历算法
- 77.常用遍历算法-for_each
- 78.常用遍历算法-transform
- 79.常用遍历算法-find
- 80.常用查找算法-find_if
- 81.常用查找算法-adjacent_find
- 82.常用查找算法-binary_search
- 83.常用查找算法-count
- 84.常用查找算法-count_if
- 85.常用排序算法-sort
- 86.常用排序算法-random_shuffle
- 87.常用排序算法-merge
- 88.常用排序算法-reverse
- 算法主要是由头文件
<algorithm>、<functional>、<numeric>
组成。 <algorithm>
是所有STL头文件中最大的一个,范围涉及到比较、交换、查找、遍历操作、复制、修改
等等<numeric>
体积很小,只包括几个在序列上面进行简单数学运算的模板函数<functional>
定义了一些模板类,用以声明函数对象
77.常用遍历算法-for_each
for_each ---->遍历容器
功能描述:
实现遍历容器
函数原型;
for_each(iterator beg, iterator end,_func) ;
// 遍历算法遍历容器元素
// beg开始迭代器
// end结束迭代器
// _func函数或者函数对象
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//常用遍历算法 for_each
// 普通函数
void print01(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_each(v.begin(), v.end(), print01);
cout << endl;
for_each(v.begin(), v.end(), print02());
cout << endl;
}
int main()
{
test01();
return 0;
}
总结: for_each在实际开发中是最常用遍历算法,糖要熟练掌握