min_element和max_element

时间复杂度:O(n)
头文件:algorithm
min_element(st, ed):返回地址[st, ed)中最小的那个值的地址(迭代器)
max_element(st, ed):返回地址[st, ed)中最大的那个值的地址(迭代器)

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main(){
	vector<int> a = {5, 6, 3, 2};
	//或者使用auto it = min_element(a.begin(), a.begin() + 2);
	vector<int>::iterator it = min_element(a.begin(), a.begin() + 2);
	cout<<*it;
	
	int b[] = {4, 7, 8, 9};
	int it1 = *max_element(b, b + 2);
	cout<<it1;
	return 0;
}

nth_element

时间复杂度:O(n)
头文件:algorithm
nth_element(st, k, ed):进行部分排序,返回值为void,将第k位置元素处于正确位置,前面的比它小,后面的比它大

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main(){
	vector<int> a = {6, 2, 3, 7, 9};
	nth_element(a.begin(), a.begin() + 2, a.end());
	cout<<a[2];
	
	int b[] = {3, 2, 6, 1, 8};
	nth_element(b, b + 2, b + 5);
	cout<<b[2];
	return 0;
}

binary_search

时间复杂度:O(logn)
头文件:algorithm
binary_search(st, ed, target):返回值为bool,通过二分查找确定序列中是否存在目标元素

lower_bound、upper_bound

时间复杂度:O(logn)
头文件:algorithm
使用前提:数组必须非降序
如果要在非升序的数组中使用,可以通过修改比较函数实现
lower_bound(st, ed, x):返回[st, ed)中第一个大于等于x的元素地址
upper_bound(st, ed, x):返回[st, ed)中第一个大于x的元素地址
如果不存在则返回最后一个元素的下一个地址,end()或n
地址 - 首地址 = 下标

sort

时间复杂度:O(nlogn)
头文件:algorithm
sort(st, ed, 比较函数或lambda表达式):返回值是void,将数组排序,默认是从小到大

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

bool cmp(const int &u, const int &v){
	return u > v;
}

int main(){
	vector<int> a = {1, 3, 5, 7, 9};
	//或sort(v.begin(), v.end(), [](const int &u, const int &v){ return u > v; }); 
	sort(a.begin(), a.end(), cmp); 
	for(auto it : a) cout<<it<<endl;
	return 0;
}

//或重载小于号
struct Node{
	int u;
	bool operator < (const Node &m) const{
		return u > m.u;
	}
}; 
int main(){
	Node a[] = {5, 7, 9, 3, 1};
	sort(a, a + 5); 
	for(auto it : a) cout<<it.u<<endl;
	return 0;
}

memset

头文件:cstring
memset(void* ptr, int value, size_t num):返回一个指向ptr的指针,将ptr指向的内存块的前num个字节设置为value的值,重置一个数组,例如memset(a, 0, sizeof(a));
ptr:指向设置值的内存块
value:设置的值,一个八位二进制数
num:要设置的字节数

int main(){
	int a[5];
	memset(a, 1, sizeof a);
	//设置成1就是:00000001000000010000000100000001
	//设置成0x3f就是:十六进制前四位是3,后面一位是f,00111111001111110011111100111111
	//设置成0、-1则不变
	for(int i = 0; i < 5; i++) cout<<bitset<32>(a[i])<<endl;
	return 0;
}

swap

swap(T &a, T &b):交换任意类型的变量

reverse

头文件:algorithm
reverse(st, ed):反转一个数组、向量、字符串

unique

时间复杂度:O(n)
头文件:algorithm
使用前提:进行排序
unique(st, ed):将[st, ed)范围内相邻重复元素去除,返回值是去重后重复元素的第一个位置
1 2 2 3 5 5 -> 1 2 3 5 2 5

islower、isupper

头文件:cctype
islower©:返回值bool,判断一个字符是否是小写或大写字母

tolower、toupper

tolower©:返回一个字符,如果c是大写字母就转化成小写字母

acsii码

大写字母转换为小写字母:c + 32 或 c - ‘A’ + ‘a’
小写字母转换为大写字母:c - 32 或 c - ‘a’ + ‘A’
字符转化成数字:‘6’ - ‘0’ = 6

next_permutation、prev_permutation

next_permutation(st, ed):生成当前序列的下一个排列,返回true,如果已经是最后一个排列,则更改为第一个排列,返回false
prev_permutation相反

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐