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

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

相关推荐
叫我辉哥e11 天前
### 技术文章大纲:C语言造轮子大赛
c语言·开发语言
guygg881 天前
NOMA功率分配与64 QAM调制中的SIC的MATLAB仿真
开发语言·matlab
TracyCoder1231 天前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
flushmeteor1 天前
JDK源码-基础类-String
java·开发语言
u0109272711 天前
C++中的策略模式变体
开发语言·c++·算法
2501_941837261 天前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
雨季6661 天前
构建 OpenHarmony 简易文字行数统计器:用字符串分割实现纯文本结构感知
开发语言·前端·javascript·flutter·ui·dart
雨季6661 天前
Flutter 三端应用实战:OpenHarmony 简易倒序文本查看器开发指南
开发语言·javascript·flutter·ui
进击的小头1 天前
行为型模式:策略模式的C语言实战指南
c语言·开发语言·策略模式
Aevget1 天前
MFC扩展库BCGControlBar Pro v37.2新版亮点:控件功能进一步升级
c++·mfc·界面控件