STL常用算法(一)《遍历》(学习)

概念:

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

1、常用遍历算法

for_each

#include<iostream>
#include<algorithm>
using namespace std;
#include<vector>

void print01(int val)
{
	cout << val << " ";
}

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);
	}

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

}

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

 transform

#include<iostream>
#include<algorithm>
using namespace std;
#include<vector>

class myprint
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
class mytransform
{
public:
	int operator()(int val)
	{
		return val;
	}
};
void test01()
{
	vector<int>v;
	for (int i = 0;i < 10;i++)
	{
		v.push_back(i);
	}
	vector<int>target;
	target.resize(v.size());
	transform(v.begin(), v.end(), target.begin(), mytransform());
	for_each(target.begin(), target.end(), myprint());

}

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值