求数组最值

  1. vector<int> t;
  2. //get max element
  3. int max_val = max_element(t.begin(), t.end());
  4. //get min element
  5. int min_val = min_element(t.begin(), t.end());
  6. //get both max and min element
  7. auto [mn, mx] = minmax_element(t.begin(), t.end());

数组求和

accumulate定义在#include
accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值。
accumulate函数将它的一个内部变量设置为指定的初始值,然后在此初值上累加输入范围内所有元素的值。accumulate算法返回累加的结果,其返回类型就是其第三个实参的类型。

  1. vector<int> t;
  2. int sum = accumulate(t.begin(), t.end(), 0)

判断字符是否是数字或字母

以下函数的声明在头文件

  1. isalpha

isalpha()用来判断一个字符是否为字母,如果是字符则返回非零,否则返回零。

  1. cout<<isalpha('a'); //返回非零
  2. cout<<isalpha('2'); //返回0
  1. isalnum

isalnum()用来判断一个字符是否为数字或者字母,也就是说判断一个字符是否属于az||AZ||0~9

  1. cout<<isalnum('a'); //输出非零
  2. cout<<isalnum('2'); // 非零
  3. cout<<isalnum('.'); // 零

大小写判断及转换

以下函数的声明在头文件

  1. islower

islower()用来判断一个字符是否为小写字母,也就是是否属于a~z。

  1. cout<<islower('a'); //非零
  2. cout<<islower('2'); //输出0
  3. cout<<islower('A'); //输出0
  1. isupper

isupper()和islower相反,用来判断一个字符是否为大写字母。

  1. cout<<isupper('a'); //返回0
  2. cout<<isupper('2'); //返回0
  3. cout<<isupper('A'); //返回非零
  1. tolower

tolower()函数是把字符串都转化为小写字母

  1. string str= "THIS IS A STRING";
  2. for (int i=0; i <str.size(); i++)
  3. str[i] = tolower(str[i]);
  1. toupper

toupper()函数是把字符串都转化为小写字母

  1. string str= "hahahahaha";
  2. for (int i=0; i <str.size(); i++)
  3. str[i] = toupper(str[i]);

数组二分查找

lower_bound( )upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。

  1. 在从小到大的排序数组中,

lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

  1. 在从大到小的排序数组中,重载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,得到找到数字在数组中的下标。

寻找字符串中字符下标

  1. string a = "abc ss";
  2. int pos = a.find_first_of(" "); // 返回第一个空格的下标

stoi & atoi

ostringstream、istringstream、stringstream

  1. #include<iostream>
  2. #include<sstream> //istringstream 必须包含这个头文件
  3. #include<string>
  4. using namespace std;
  5. int main()
  6. {
  7. string str="i am a boy";
  8. istringstream is(str);
  9. string s;
  10. while(is>>s) {
  11. cout<<s<<endl;
  12. }
  13. }
  14. // i
  15. // am
  16. // a
  17. // boy