STL常用遍历算法

概述:

  • 算法主要是由头文件<algorithm> <functional> <numeric>组成。

  • <algorithm>是所有STL头文件中最大的一个,范围涉及到比较、 交换、查找、遍历操作、复制、修改等等

  • <numeric>体积很小,只包括几个在序列上面进行简单数学运算的模板函数

  • <functional>定义了一些模板类,用以声明函数对象。

1 常用遍历算法

算法简介:

  • for_each //遍历容器
  • transform //搬运容器到另一个容器中

1.1 for_each

功能描述:

  • 实现遍历容器

函数原型:

  • for_each(iterator beg, iterator end, _func);

    // 遍历算法 遍历容器元素

    // beg 开始迭代器

    // end 结束迭代器

    // _func 函数或者函数对象

cpp 复制代码
#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;
	cout << "---------------";
	cout << endl;
	for_each(v.begin(), v.end(), print02());
}

int main()
{
	test01();
	return 0;
}

1.2 transform

功能描述:

  • 搬运容器到另一个容器中

函数原型:

  • transform(iterator beg1, iterator end1, iterator beg2, _func);

//beg1 源容器开始迭代器

//end1 源容器结束迭代器

//beg2 目标容器开始迭代器

//_func 函数或者函数对象

cpp 复制代码
#include<iostream>
#include <vector>
#include <algorithm>

using namespace std;

//常用算法遍历transform

class Transform
{
public:
	int operator()(int v)
	{
		return v;
	}
};

class print
{
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(),print());
}

int main()
{
	test01();
	return 0;
}

搬运的目标容器必须要提前开辟空间,否则无法正常搬运

相关推荐
云和数据.ChenGuang7 分钟前
PHP-FPM返回的File not found.”的本质
开发语言·php·运维工程师·运维技术
R.lin23 分钟前
Java 8日期时间API完全指南
java·开发语言·python
旖旎夜光30 分钟前
多态(11)(下)
c++·学习
yongui4783435 分钟前
MATLAB的指纹识别系统实现
算法
高山上有一只小老虎36 分钟前
翻之矩阵中的行
java·算法
yangpipi-40 分钟前
《C++并发编程实战》 第4章 并发操作的同步
开发语言·c++
jghhh0144 分钟前
RINEX文件进行卫星导航解算
算法
火钳游侠1 小时前
java单行注释,多行注释,文档注释
java·开发语言
Chance_to_win1 小时前
C++基础知识
c++
爱思德学术1 小时前
中国计算机学会(CCF)推荐学术会议-A(计算机科学理论):LICS 2026
算法·计算机理论·计算机逻辑