algorithm头文件函数全集——史上最全,最贴心-程序员宅基地

技术标签: 算法  c++  stl  acm竞赛  积累  algorithm  


2022.4.8更:

随着本篇博客观看次数越来越多,假如有一点点疏忽,就可能造成更大的影响, 因此采取动态维护的策略:

从今天开始,每天我会检查评论区, 及时解答大家的疑问,修改可能存在的问题 如果哪里写的有疏漏,也欢迎批评指出!


简介:

algorithm头文件是C++的标准算法库,它主要应用在容器上。 因为所有的算法都是通过迭代器进行操作的,所以算法的运算实际上是和具体的数据结构相分离的 ,也就是说,具有低耦合性。 因此,任何数据结构都能使用这套算法库,只要它具有相应的迭代器类型

常用函数:

一、max()、min()、abs()函数

max():求两个数最大值
min():求两个数最小值
abs():求一个数的绝对值

代码:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
    
	int a = 3, b = 4;
	//求最大值
	int Max = max(a,b);
	//求最小值
	int Min = min(a,b);
	//求绝对值
	int Abs = abs(-3);
	cout << Max << Min << Abs;
	
	return 0;
 } 

输出:433

注意:

1、max()min()函数中的参数只能是两个如果想求3个数的最大值,需要嵌套一下
同理:如果想求数组中的最大值,需要在循环中写。
2、写了algorithm头文件后, max就变成了函数名,在自己定义变量时,要避免使用max,min等
3、abs()函数只能用于求整型变量的绝对值,而#include<cmath>中的fabs()函数还可用于求浮点型变量的绝对值,不要搞混~



2、交换函数:swap()

用来交换x和y的值

代码:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
    
	int a = 3, b = 4;
	swap(a,b);
	cout << a << b;
	return 0;
 } 

输出:43



3、翻转函数:reverse()

翻转x-y区间的数组、容器的值。
1、翻转整个数组

翻转整个数组:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
    
	int a[5] = {
    11,22,33,44,55};
	reverse(a,a+5);
	for(int i = 0; i < 5; i++) 
		cout << a[i] << ' ';
	return 0;
 } 

输出:55 44 33 22 11

2、也可以实现对部分值的翻转,像这样:

翻转部分数组:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
    
	int a[5] = {
    11,22,33,44,55};
	reverse(a+3,a+5);
	for(int i = 0; i < 5; i++) 
		cout << a[i] << ' ';
	return 0;
 } 

输出:11 22 33 55 44

3、翻转容器:若想对容器中所有的数进行翻转,则需要用到begin()、end()函数,像这样:

翻转整个容器:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
    
	vector<int>v;
	//输入: 
	for(int i = 0; i < 5; i++) 
		v.push_back(i);
	//输出: 
	reverse(v.begin(), v.end());
	for(int i = 0; i < v.size(); i++) {
    
		cout << v[i] << ' ';
	}
	return 0;
 } 

输出:4 3 2 1 0

4、翻转容器:容器的翻转也可以用迭代器,来实现指定位数的翻转,像这样:

翻转部分容器:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
    
	vector<int>v;
	vector<int>::iterator it;
	//输入: 
	for(int i = 0; i < 5; i++) 
		v.push_back(i);
	//输出: 
	it = v.begin(); 
	reverse(it, it+3);
	for(int i = 0; i < v.size(); i++) {
    
		cout << v[i] << ' ';
	}
	return 0;
 } 

输出:2 1 0 3 4

注意:

如果想在翻转时指定位数,则其为半开半闭区间。 如reserve(a+2, a+4);翻转数组中第2-4之间的数,不包括第二个,但包括第四个。



四、排序函数:sort()

1、对x-y区间的数组、容器进行排序。默认升序排列

数组升序排序:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
    
	int a[5] = {
    55,44,33,22,11};
	
	sort(a,a+5);
	
	for(int i = 0; i < 5; i++) 
		cout << a[i] << ' ';
		
	return 0;
 } 

输出:11 22 33 44 55

2、如果想将数组降序排序,就需要写一个简单的函数,改变默认的排序功能,像这样:

数组降序排序:
#include<iostream>
#include<algorithm>
//意思是:若a>b,则a的优先级更大! 也就是说大的在前面。
bool cmp(int a, int b) {
    
	return a > b; 
}
using namespace std;
int main() {
    
	int a[5] = {
    55,44,33,22,11};
	
	sort(a,a+5,cmp);			//这里需要加上自己自定义的函数
	
	for(int i = 0; i < 5; i++) 
		cout << a[i] << ' ';
	return 0;
 } 

输出:55 44 33 22 11

3、同理,如果想对结构体排序,也需要自定义优先级。像这样:

结构体排序:
#include<iostream>
#include<algorithm>
using namespace std;
//用sort函数对结构体排序 
struct Student {
    
	int high;
	int weigh;
}student[10];
//a.high如果小于b.high,则a结构体的优先级更大, 也就是说:high小的结构体排在前面。 
bool cmp(Student a, Student b) {
    
	return a.high < b.high;
} 
int main() {
    
	for(int i = 0; i < 10; i++) {
    
		student[i].high = i ;
	}
	sort(student, student+10, cmp);		//将自定义的函数添加上。
	
	for(int i = 0; i < 10; i++) {
    
		cout << student[i].high << ' ';
	}
	return 0;
}

输出:0 1 2 3 4 5 6 7 8 9

4、如果想对容器排序,就需要使用迭代器,或begin(),end()函数。像这样:

容器升序排序:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
    
	vector<int>v;
	vector<int>::iterator it;
	//输入: 
	for(int i = 5; i > 0; i--) 
		v.push_back(i); 
	//输出: 
	it = v.begin(); 
	sort(it, it+3);
//	sort(v.begin(), v.end())
	for(int i = 0; i < v.size(); i++) {
    
		cout << v[i] << ' ';
	}
	return 0;
 } 

输出:3 4 5 2 1
5、同理,如果想对容器降序排序,或对容器结构体排序,向数组那样操作就可以了。

注意:

1、sort()排序函数的时间复杂度大概在o(nlogn),比冒泡、简单排序等效率高
2、和reverse()函数一样,可以自由指定排序范围,也是半开半闭区间(左闭右开)



五、查找函数:find()
查找某数组指定区间x-y内是否有x,若有,则返回该位置的地址,若没有,则返回该数组第n+1个值的地址。(好烦有木有,为啥要返回地址。还要转化o(╥﹏╥)o)

1、数组中查找是否有某值:一定一定一定要满足代码中这两个条件。
第一个条件是:p-a != 数组的长度。p是查找数值的地址,a是a[0]的地址。
第二个条件是:*p == x; 也就是该地址指向的值等于我们要查找的值。
最后输出p-a+1; p-a相当于x所在位置的地址-a[0]所在位置的地址, 但因为是从0开始算, 所以最后需要+1。

对数组查找:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
      
	int a[5] = {
    11,22,33,44,55}	
	
	int *p = find(a,a+5,33);				//定义指针,指向查找完成后返回的地址,5为a2数组长度 
  	if(((p-a) != 5) && (*p == x))		//若同时满足这两个条件,则查找成功,输出 
  		cout << (p-a+1);					//输出所在位置 
	return 0;
 } 

输出:3

2、对容器进行查找同理:也要满足这两个条件:

对容器查找:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
    
	vector<int>v;
	vector<int>::iterator it, it1;
	//输入: 
	for(int i = 0; i < 5; i++) 
		v.push_back(i); 
	//查找 
	int size = v.size();					//第一步:求长度
	it = find(v.begin(), v.end(), 3);		//第二步:查找x在容器的位置,返回迭代器1
	it1 = v.begin();						//第三步:令迭代器2指向容器头 
	if(((it-it1)!=size)&&(*it==3))			//第四步:若同时满足这两个条件,则查找成功,输出 
		cout << (it-it1+1) << endl;			//输出所在位置 
	return 0;
 } 

输出:4



六、查找函数:upper_bound()、lower_bound()

1、upper_bound():查找第一个大于x的值的位置
2、lower_bound():查找第一个大于等于x的值的位置
同样是返回地址,用法和find()函数一毛一样,限制条件也一毛一样,照着扒就行了。



七、填充函数:fill()

在区间内填充某一个值。同样适用所有类型数组,容器
1、举例:在数组中未赋值的地方填充9999

代码:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
      
	int a[5] = {
    11,33,22};
	
	fill(a+3,a+5,9999);								
	
	for(int i = 0; i < 5; i++) 
		cout << a[i] << ' ';
	return 0;
 } 

输出:11 33 22 9999 9999

应用:

常用在大数加法中,因为数太大,需要用字符串保存,如果在运算时需要填充0,就要用这个函数。



八、查找某值出现的次数:count()

1、在数组中查找x 在某区间出现的次数:

代码:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
      
	int a[5] = {
    11,22,33,44,44};
	
	cout << count(a, a+5, 44);	
	
	return 0;
 } 

输出:2

2、在容器中查找同理,只是需要用iterator迭代器或begin()end()函数。

注意:

和前几个函数一样,如果需要指定区间查询,注意是半开半闭区间(左闭右开区间)



八、求最大公因数:__gcd()

震惊把!在我最开始知道竟然有这个函数时,我也是震惊的!
另外,用二者乘积除以最大公因数即可得到最小公倍数。 因此没有求最小公倍数的函数。

代码:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
      
	int a = 12, b = 4;
	int Gcd = __gcd(a,b);
	cout << Gcd;
	return 0;
 } 
注意:

__gcd() 需要写两个下划线!



九、求交集、并集、差集:set_intersection()、set_union()、set_difference()

1、求交集:
(1):将两个数组的交集赋给一个容器(为什么不能赋给数组呢?因为数组不能动态开辟,且inserter()函数中的参数必须是指向容器的迭代器。):

代码:
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
int main() {
    
	int a[5] = {
    1,2,3,4,5}, b[5] = {
    1,2,33,44,55};
	vector<int>::iterator it;
	vector<int>v4;	
	set_intersection(a, a+5, b, b+5, inserter(v4,v4.begin()));
	for(int i = 0; i < v4.size(); i++) {
    
		cout << v4[i] << ' ';
	}

输出:1 2
(2):将两个容器的交集赋给另一个容器:

代码:
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
int main() {
    
	vector<int> v1, v2, v3;
	for(int i = 0; i < 5; i++) 
		v1.push_back(i);
	for(int i = 3; i < 8; i++) 
		v2.push_back(i);
	  
	set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), inserter(v3,v3.begin()));  
	for(int i = 0; i < v3.size(); i++) {
    
		cout << v3[i] << ' ';
	}
	return 0;
} 

输出:3 4

2、求并集:
(1):将两个数组的并集赋给一个容器(为什么不能赋给数组呢?因为数组不能动态开辟,且inserter()函数中的参数必须是指向容器的迭代器。):

代码:
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
int main() {
    
	int a[5] = {
    1,2,3,4,5}, b[5] = {
    1,2,33,44,55};
	vector<int>::iterator it;
	vector<int>v4;	
	set_union(a, a+5, b, b+5, inserter(v4,v4.begin()));
	for(int i = 0; i < v4.size(); i++) {
    
		cout << v4[i] << ' ';
	}

输出:1 2 3 4 5 33 44 55
(2):将两个容器的并集赋给另一个容器:

代码:
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
int main() {
    
	vector<int> v1, v2, v3;
	for(int i = 0; i < 5; i++) 
		v1.push_back(i);
	for(int i = 3; i < 8; i++) 
		v2.push_back(i);
	  
	set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), inserter(v3,v3.begin()));  
	for(int i = 0; i < v3.size(); i++) {
    
		cout << v3[i] << ' ';
	}
	return 0;
} 

输出:0 1 2 3 4 5 6 7

3、差集完全同理。

注意:

inserter(c,c.begin())为插入迭代器
此函数接受第二个参数,这个参数必须是一个指向给定容器的迭代器。元素将被插入到给定迭代器所表示的元素之前。



十、全排列:next_permutation()

将给定区间的数组、容器全排列
1、将给定区间的数组全排列:

代码:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
      
	int a[3] = {
    1,2,3};
	do{
    
		cout<<a[0]<<a[1]<<a[2]<<endl; 
	}while(next_permutation(a,a+3));	//输出1、2、3的全排列 
	
	return 0;
 } 

输出:
123
132
213
231
312
321

2、容器全排列同理:只不过将参数换成iterator迭代器或begin()end()函数。

注意:

和之前的一样,如果指定全排列区间,则该区间是半开半闭区间(左闭右开)


/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         I have a dream! An AC dream!!
         */

如果哪里有困惑,欢迎给笔者留言。

如果这篇博文对你产生了帮助,可以留下小小的一个赞哦,大家的支持是我更新的最大动力~

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43899069/article/details/104450000

智能推荐

Monte-Carlo Dropout,蒙特卡罗 dropout-程序员宅基地

文章浏览阅读4.4k次,点赞11次,收藏55次。Monte-Carlo DropoutMonte-Carlo Dropout(蒙特卡罗 dropout),简称 MC dropout。一种从贝叶斯理论出发的 Dropout 理解方式,将 Dropout 解释为高斯过程的贝叶斯近似。云里雾里的,理论证明看起来挺复杂,有兴趣可以参考论文:Dropout as a Bayesian Approximation: Representing..._mc dropout

详细图文一步步记录Spring 5.3源码编译和调试(IDEA+Gradle)的过程_idea gradle怎么编译-程序员宅基地

文章浏览阅读2.2k次,点赞4次,收藏12次。1 前言最近稍微研究了一下spring源码,看了不少资料发现不少大佬都是将spring源码拉到本地,自己编译完成之后在源码里面直接写注释,当然也更方便了自己学习和调试。所以我也做了一次尝试,在此记录一下编译的过程和遇到的问题。2 环境准备本地编译spring源码我使用的个软件版本如下:系统:Mac os Big SurIDEA:2020.1.2gradle:6.8.3spring: 5.3.7-SNAPSHOTjdk:11.0.113 Spring编译流程3.1 下载安装gradle_idea gradle怎么编译

php生成excel文件_withstartrow false 不生效-程序员宅基地

文章浏览阅读241次。<?php function createExcel($list, $indexKey, $filename = "", $startRow = 1, $excel2007 = false){ require_once APPLICATION_PATH . '/PHPExcel/PHPExcel.php'; require_once APPLICATION_PATH . ..._withstartrow false 不生效

Typora多行公式自动编号+引用_typora公式编号-程序员宅基地

文章浏览阅读1.1w次,点赞21次,收藏43次。Typora公式自动编号文章目录Typora公式自动编号手动键入tag简单公式解决方法公式对齐不能自动编号的问题手动键入tag键入手动方法后加\tag,如行间直接键入$$y=ax+b \tag 1$$y=ax+b(1)y=ax+b \tag{1}y=ax+b(1)这样的问题是公式没有居中手动添加编号效率太低,如果中间插入一个公式,后面的都要动简单公式解决方法公式插入按快捷键而不是直接在行间键入,注意,似乎手动按格式输入不行,必须要用快捷键插入。默认的快捷键是Ctrl+Shift+K_typora公式编号

使用滚动条来显示<el-tree>组件溢出的内容_el-tree节点溢出-程序员宅基地

文章浏览阅读437次。<div style="height:650px;overflow:auto;"> <el-tree></er-tree></div>在<el-tree>组件外面包裹一个divoverflow:auto;如果内容被修剪,则浏览器会显示滚动条以便查看其余的内容。overflow:scoll;内容会被修剪,但是浏览器会显示滚动条以便查看其余的内容。【注意】:设置元素的长度,长度范围小于背景范围。..._el-tree节点溢出

随便推点

制作简单的WPF时钟_wpf中时钟控件,可以绑定system.datetime.now吗-程序员宅基地

文章浏览阅读1.2w次。在很早之前,我曾经写过一个GDI+的时钟,见“C#时钟控件 (C# Clock Control)” http://blog.csdn.net/johnsuna/archive/2006/02/13/597746.aspx及“使用C#编写LED样式时钟控件”(http://blog.csdn.net/johnsuna/archive/2006/02/14/598867.aspx),进入WPF时代了,_wpf中时钟控件,可以绑定system.datetime.now吗

【漏洞复现】Fastjson反序列化_fastjson反序列化漏洞复现-程序员宅基地

文章浏览阅读5.4k次,点赞7次,收藏35次。Fastjson反序列化一、简介二、序列化与反序列化三、Fastjson漏洞介绍1、漏洞原理2、RMI3、JNDI4、JEP290四、编写的简单测试的环境五、漏洞版本1、fastjson<=1.2.241.1、TemplatesImpl 利用链分析1.2、JNDI利用链分析1.3、JNDI利用1.4、官方进行的修复2、fastjson<=1.2.413、fastjson<=1.2.424、fastjson<=1.2.455、fastjson<=1.2.476、1.2.48<_fastjson反序列化漏洞复现

【大数据】Hbase如何批量删除指定数据-程序员宅基地

文章浏览阅读878次。一、起因:  Hbase是一个列式存储,nosql类型的数据库,类似mongodb。  目前似乎没有提供批量删除的方法,只有一个单行删除的命令:deleteall 'tablename', rowkey二、删除方法:  方法一:通过写 shell 脚本,从 hbase shell 查出需要删除的 rowkey ,拼成删除命令(deleteall 'tablename', ro..._hbase命令删除多条记录

【Java】方法中的参数传递机制的具体体现_说明java方法中的参数传递机制的具体体现?-程序员宅基地

文章浏览阅读3.1k次。while循环和do-while循环区别While:符合条件时执行Do-while:先做一次再说,之后符合条件时执行_说明java方法中的参数传递机制的具体体现?

Confluent.Kafka 在.net core下的坑_failed to load the librdkafka native library.-程序员宅基地

文章浏览阅读7.4k次。centos 下运行报错:Unhandled Exception: System.DllNotFoundException: Failed to load the librdkafka native library. at Confluent.Kafka.Impl.LibRdKafka.Initialize(String userSpecifiedPath) in C:\Users\sugar..._failed to load the librdkafka native library.

wpa_supplicant 状态机的切换以及事件驱动_enum wpa_event_type 详解-程序员宅基地

文章浏览阅读7.6k次,点赞6次,收藏25次。wpa_supplicant 状态机的切换adb logcat | findstr "wpa_supplicant:.wlan0:.State:"1.一次打开WIFI自动连接的过程09-29 20:53:59.796 4882 4882 D wpa_supplicant: wlan0: State: DISCONNECTED -> DISCONNECTED09-29 2_enum wpa_event_type 详解

推荐文章

热门文章

相关标签