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

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

相关推荐
lly2024061 小时前
Bootstrap 警告框
开发语言
2601_949146532 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
你撅嘴真丑2 小时前
第九章-数字三角形
算法
曹牧2 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
在路上看风景2 小时前
19. 成员初始化列表和初始化对象
c++
KYGALYX2 小时前
服务异步通信
开发语言·后端·微服务·ruby
uesowys2 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
zmzb01032 小时前
C++课后习题训练记录Day98
开发语言·c++
ValhallaCoder2 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮2 小时前
AI 视觉连载1:像素
算法