学习目标:
- 掌握常用的变量算法
算法简介:
for_each//遍历算法
transform//搬运容器到另一个容器
for_each
#include <iostream>
using namespace std;
//常用遍历算法
#include <vector>
#include<algorithm>
//普通函数
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();
}
运行结果:
transform
功能描述:
- 搬运容器到另一个容器中
#include <iostream>
using namespace std;
//常用遍历算法 transform
#include <vector>
#include<algorithm>
class Transform
{
public:
int operator()(int v)
{
return v;
}
};
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>v2;//目标文件
//目标文件需要提前开辟空间
v2.resize(v.size());
transform(v.begin(), v.end(), v2.begin(), Transform());
for_each(v2.begin(), v2.end(), myPrint());
cout << endl;
}
int main()
{
test01();
}