刷题常用函数

整理在leetcode刷题经常用到的函数。

char toupper(char c)

​ 将小写字母c转为大写字母返回。

char tolower(char c)

​ 将大写字母c转为小写字母返回。

bool isalpha(char c)

​ 判断输入的字符是否为字母,即是否在 “A – Z” 或者 “a – z”之间,是字母则返回true,不是字符则返回false。

bool isalnum(char c)

判断输入的字符是否为字母或者数字,即是否在 “A – Z” 或者 “a – z” 或者”0 – 9”之间,在这些范围内返回true,不在则返回false。

bool isdigit(char c)

判断输入的字符是否为数字。

bool isupper(char c)

判断输入的字符是否为大写字母。

bool islower(char c)

判断输入的字符是否为小写字母。

int stoi(const string&str, size_t* idx = 0, int base = 10)

从下标idx开始,将str中找到的第一个数字部分按照base进制转成10进制数返回。

如果 idx不是空指针,则该函数还会将 idx的值设置为 str 中第一个字符在数字之后的位置。

参考:https://cplusplus.com/reference/string/stoi/

string to_string(typeNum val)

将val转成字符串返回。

max_element(起始迭代器, 结束迭代器, 自定义操作函数)

返回最大值的地址,最大值的判断方法由第三个自定义操作函数定义,若函数没有第三参数则按数值大小。

min_element(起始迭代器, 结束迭代器, 自定义操作函数)

同max_element(起始迭代器, 结束迭代器, 自定义操作函数)。

accumulate(起始迭代器, 结束迭代器, 初始值, 自定义操作函数)

求和:无第四个参数默认进行+运算,也可用于字符串拼接。

乘积:multiplies(), 初始值设为1。

自定义函数:

1
2
3
int myfunction (int x, int y) {return x+2*y;}
int nums[] = {10, 20, 30, 40};
sum = std::accumulate(nums, nums + 4, 0, myfuction);

参考:https://cplusplus.com/reference/numeric/accumulate/

nth_element(起始迭代器, 起始迭代器 + k,结束迭代器, 自定义操作函数)

默认求第k小的值,把下标为k的数组中的元素放到了正确的位置,对于其他元素就没有进行排序,但是,在k左边的元素都是小于等于它的,而在k右边的元素都是大于等于它的。

求第k大的,自定义函数写greater()。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<bits/stdc++.h>
using namespace std;
bool compare(int a, int b){
return a > b;//第k大
}
int main(){
int a[9] = {4,7,6,9,1,8,2,3,5};
int b[9] = {4,7,6,9,1,8,2,3,5};
int c[9] = {4,7,6,9,1,8,2,3,5};
nth_element(a,a+2,a+9);
cout <<"第3小是:"<< a[2] << endl;
nth_element(b,b+6,b+9);
//nth_element(b,b+2,b+9,greater<int>());
cout <<"第3大是:"<< b[6] << endl;
nth_element(c,c+2,c+9,compare);
cout <<"第3大是:"<< c[2] << endl;
}
//nth_element得到的元素序列是乱序的,但是第k个元素位置是正确的