C++ STL常用算法

目录

前言

一、常用的遍历算法

1.1 for_each

1.2 transform 

二、常见的查找算法

2.1 find()

2.2 find_if

2.3 adjacent_find

2.4 binary_search

2.5 count_if

三、常用的排序算法

3.1 random_shuffle洗牌算法

3.2 merge

3.3 reverse 反转排序算法

四、常用拷贝和替换算法

五、常用算术生成算法

5.1 accumulate 

5.2 fill

六、常用的集合算法

6.1 set_intersection 交集

6.2 set_union 并集

6.3 set_difference 差集

总结


前言

在使用STL算法时需要包含有关头文件。主要是由头文件<algorithm> <functional> <numeric>组成。

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

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

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


一、常用的遍历算法

遍历算法语法:

for each  //遍历容器

transform  //搬运容器到另一个容器中

1.1 for_each

功能描述:实现遍历容器

函数原型: for each(iterator beg, iterator end, func);   // 遍历算法 遍历容元素

下面为使用普通函数遍历和使用仿函数遍历的方法。需要注意的是在使用普通函数时,在for_each() 中不加(),因为要传递的是函数的地址(即为函数指针)。在使用仿函数时,需要(),传入的是一个匿名对象类。

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//常用遍历算法 for_each
//1.普通函数
void print(int a)
{
	cout << a << " ";
}
//仿函数
class print2
{
public:
	void operator()(int a)
	{
		cout << a << " ";
	}
};
void test01()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	for_each(v.begin(), v.end(), print);//这里print 不加() 因为这里传递的是函数的地址(函数指针)
	cout << endl;
	for_each(v.begin(), v.end(), print2());//这里加() 仿函数是一个类加()是传入一个匿名对象类
}
int main()
{
	test01();
	system("pause");
	return 0;
}

1.2 transform 

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

需要注意:搬运的目标容器必须要提前开辟空间,用 resize() 指定容器的容量,否则无法正常搬运。

二、常见的查找算法

查找算法语法:

1.  find  //查找元素

2.  find_if  //按条件查找元素

3.  adjacent_find  //查找相邻重复元素

4.  binary_search  //二分查找法

5.  count  //统计元素个数

6.  count_if  //按条件统计元素个数

2.1 find()

find() 功能概述:查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end()

函数原型:  find(iterator beg, iterator end, value) ;

自定义数据类型时,使用 find() 函数前需要重载 “==” 号。下面为一个自定义类,在使用 find()查找时,需要在 person 类中利用布尔类型重载“==”号,其中传入的参数需要用const声明,防止值被修改。代码如下所示:

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
class person
{
public:
	person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	//重载 == 让底层find知道如何对比person数据类型
	bool operator==(const person &p1)
	{
		if (this->m_name == p1.m_name && this->m_age == p1.m_age)
		{
			return true;
		}
		els