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

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

相关推荐
你真是饿了16 小时前
算法专题二:滑动窗口
算法
Jordannnnnnnn16 小时前
追赶33名
c++
ccLianLian16 小时前
数论·约数
数据结构·算法
会编程的土豆16 小时前
【数据结构与算法】最短路径---Dijkstra 算法
数据结构·c++·算法
2401_8796938716 小时前
C++中的观察者模式实战
开发语言·c++·算法
炽烈小老头17 小时前
【 每天学习一点算法 2026/03/24】寻找峰值
学习·算法
William_wL_17 小时前
【C++】string的实现
c++
工頁光軍17 小时前
基于Python的Milvus完整使用案例
开发语言·python·milvus
wregjru17 小时前
【网络】8.五种 I/O 模型与多路转接详解
开发语言·php
fff98111817 小时前
C++与Qt图形开发
开发语言·c++·算法