好用的小函数

一.二分查找函数

int t=lower_bound(a+l,a+r+1,x)-a

lower_bound()返回区间[l,r]中第一个大于等于x的数的迭代器
则t为a数组中第一个大于等于x的数的下标
即a[t]>=x
若均小于x,则t=r+1

int t=upper_bound(a+l,a+r+1,x)-a

upper_bound()返回区间[l,r]中第一个大于x的数的迭代器
则t为a数组中第一个大于x的数的下标
即a[t]>x
若均小于等于x,则t=r+1

二.全排列函数next_permutation()

next_permutation(a+l,a+r+1)

对a数组中的[l,r]区间元素进行全排列
若还有排列方式,a数组自动变换至下一排列,且函数返回true
否则,函数返回flase

含有n个元素的总时间复杂度为O(n!),则每次均摊复杂度为O(1)
【注意】
排列会根据数组元素的值来进行全排列。
例如:给定一个非升(降)序排列,next_以该序列的升序排列为初始排列去寻找下一排列,直至结尾。故要得到一个序列的所有全排列方式,需要对原序列先进行排序

#include<bits/stdc++.h>
using namespace std;
int a[100],n=5;
int main()
{
    
    
	for(int i=1;i<=n;i++)cin>>a[i];
	sort(a+1,a+n+1);
	do{
    
    
		for(int i=1;i<=n;i++)cout<<a[i]<<" ";
		cout<<endl;
	}while(next_permutation(a+1,a+n+1));
	
	return 0;
 } 

三.数学函数

1.log2()与log10()

返回值为double型
应用:
求整数x的十进制位数:log10(x)+1
求整数x的二进制位数:log2(x)+1

2.round()

round(x),x四舍五入到整数
应用:
对x保留t位小数:x=round(x,pow(10,t))/pow(10,t)

四.unique()

对有序数组去重,t为不重复数的位数
int t=unique(a+1,a+n+1)-a-1

猜你喜欢

转载自blog.csdn.net/weixin_43602607/article/details/110824141