求数组最值
vector<int> t;//get max elementint max_val = max_element(t.begin(), t.end());//get min elementint min_val = min_element(t.begin(), t.end());//get both max and min elementauto [mn, mx] = minmax_element(t.begin(), t.end());
数组求和
accumulate定义在#include
accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值。
accumulate函数将它的一个内部变量设置为指定的初始值,然后在此初值上累加输入范围内所有元素的值。accumulate算法返回累加的结果,其返回类型就是其第三个实参的类型。
vector<int> t;int sum = accumulate(t.begin(), t.end(), 0)
判断字符是否是数字或字母
以下函数的声明在头文件
- isalpha
isalpha()用来判断一个字符是否为字母,如果是字符则返回非零,否则返回零。
cout<<isalpha('a'); //返回非零cout<<isalpha('2'); //返回0
- isalnum
isalnum()用来判断一个字符是否为数字或者字母,也就是说判断一个字符是否属于az||AZ||0~9
cout<<isalnum('a'); //输出非零cout<<isalnum('2'); // 非零cout<<isalnum('.'); // 零
大小写判断及转换
以下函数的声明在头文件
- islower
islower()用来判断一个字符是否为小写字母,也就是是否属于a~z。
cout<<islower('a'); //非零cout<<islower('2'); //输出0cout<<islower('A'); //输出0
- isupper
isupper()和islower相反,用来判断一个字符是否为大写字母。
cout<<isupper('a'); //返回0cout<<isupper('2'); //返回0cout<<isupper('A'); //返回非零
- tolower
tolower()函数是把字符串都转化为小写字母
string str= "THIS IS A STRING";for (int i=0; i <str.size(); i++)str[i] = tolower(str[i]);
- toupper
toupper()函数是把字符串都转化为小写字母
string str= "hahahahaha";for (int i=0; i <str.size(); i++)str[i] = toupper(str[i]);
数组二分查找
lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。
- 在从小到大的排序数组中,
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
- 在从大到小的排序数组中,重载lower_bound()和upper_bound()
lower_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
寻找字符串中字符下标
string a = "abc ss";int pos = a.find_first_of(" "); // 返回第一个空格的下标
stoi & atoi
ostringstream、istringstream、stringstream
#include<iostream>#include<sstream> //istringstream 必须包含这个头文件#include<string>using namespace std;int main(){string str="i am a boy";istringstream is(str);string s;while(is>>s) {cout<<s<<endl;}}// i// am// a// boy
