今天学习遍历算法。
学习目标:
- 掌握常用的遍历算法
算法简介:
for_each
//遍历容器transform
//搬运容器到另一个容器中
1 for_each
功能描述:
- 实现遍历容器
函数原型:
-
for_each(iterator beg, iterator end, _func);
// 遍历算法 遍历容器元素
// beg 开始迭代器
// end 结束迭代器
// _func 函数或者函数对象
#include<iostream>
using namespace std;
#include<string>
#include <vector>
#include <algorithm>
//普通函数
void print01(int val)
{
cout << val<<" ";
}
//函数对象 仿函数
class print02
{
public:
void operator()(int val)
{
cout << val<<" ";
}
};
//for_each算法基本用法
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();
system("pause");
return 0;
}
总结:**for_each在实际开发中是最常用遍历算法,需要熟练掌握
5.1.2 transform
功能描述:
- 搬运容器到另一个容器中
函数原型:
transform(iterator beg1, iterator end1, iterator beg2, _func);
//beg1 源容器开始迭代器
//end1 源容器结束迭代器
//beg2 目标容器开始迭代器
//_func 函数或者函数对象
#include<iostream>
using namespace std;
#include<string>
#include <vector>
#include <algorithm>
class Transform
{
public:
int operator()(int val)
{
return val;
}
};
class print
{
public:
void operator()(int val)
{
cout << val+100<<" ";
}
};
void test01() {
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>v_trans;
v_trans.resize(v.size());
transform(v.begin(), v.end(), v_trans.begin(), Transform());
for_each(v_trans.begin(), v_trans.end(), print());
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
总结: 搬运的目标容器必须要提前开辟空间,否则无法正常搬运
打个小广告,欢迎关注我的公众号“麦香E站”,分享人工智能,信通学习,数学提高,外语学习,生活理财等多方面知识以及我多年积累的学习资源分享~
公众号后台回复 “编程” 获取我多年来积攒的海量编程电子书~
后台回复“latex”获取我倾力所作latex快速入门手册~