大小写转换
islower和isupper:检查一个字符是否是小写或者大写。
- islower:检查小写。
- isupper:检查大写。
- 函数的返回值为bool类型。
- 头文件:或者是<bits/stdc++.h>
Tolower和toupper函数:
- tolower(char ch)将ch转换为小写字母,大写不转换。
- toupper同理。
ASCII码:
- 大写字母的范围:65~90
- 小写字母的范围:97~122
大写转小写:
ch1=ch+32;//不推荐
ch1=ch-‘A’+‘a’;//减去大写的那一列,从小写的那一列开始
实现:小写转大写
#include<bits/stdc++.h>
using namespace std;
char coverch(char ch)
{
if(islower(ch))ch=toupper(ch);
else if(isupper(ch))ch=tolower(ch);
return ch;
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
string s;
getline(cin,s);
for(auto &i:s)
{
i=coverch(i);
}
cout<<s<<"\n";
}
二分查找
二分查找的前提:库函数只能对数组进行二分查找,且数组中的元素是单调的。
- 一般为单调不减,当然如果是单调不增也可以(需要修改比较函数sort)
binary_search函数:
- 用法:已排序的序列中查找特定元素。
- 通过二分查找算法来确定列中是否存在目标元素。
- 函数返回值是bool类型。
- 获取找到元素的位置使用lower_bound函数或upper_bound函数。
#include<bits/stdc++.h>
int main()
{
using namespace std;
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
vector<int>numbers={
1,3,5,7,9};
int target=5;
bool found=binary_search(numbers.begin(),numbers.end(),target);
if(found)
cout<<target<<" "<<"is found"<<endl;
else
cout<<target<<"is not found"<<endl;
return 0;
}
lower_bound和upper_bound函数
- lower_bound(start,end,target)返回地址[start,end)中第一个大于等于x的元素的地址。(注:下标=地址-首地址)
- upper_bound(start,end,target)返回地址[start,end)中第一个大于 x的元素的地址。(注意是左闭右开的区间)
- 如果不存在则返回最后一个元素的下一个位置,在vector中即end()。
- 实现
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> s={
5,1,7,3,10,18,9};
sort(s.begin(),s.end());
for(auto &i:s)
cout<<i<<' ';
cout<<"\n";
//找到数组中第一个大于等于8的元素的地址
cout<<(lower_bound(s.begin(),s.end(),8)-s.begin())<<"\n";
return 0;
}
- 例题:蓝桥1389二分查找数组
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int data[200];
for(int i = 0 ; i < 200 ; i ++)
data[i] = 4 * i + 6;
int target;
cin>>target;
cout<<lower_bound(data,data+200,target)-data<<"\n";
return 0;
}
注:不是容器(例如:vector和list)对象的不能用begin()函数。修改如下:
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
vector<int>data(200);
for(int i = 0 ; i < 200 ; i ++)
data[i] = 4 * i + 6;
int target;
cin>>target;
cout<<lower_bound(data.begin(),data.end(),target)-data.begin()<<"\n";
return 0;
}
最值查找
Min和max函数:
- 时间复杂度为O(1),传入参数为数组(用{})的时候时间复杂度为O(n),n为数组大小。
min_element和max_element函数:
- min_element(start,end)返回地址[start,end)中的最小的那个值的地址(迭代器),传入参数为两个地址或迭代器。
- Max_element(start,end)返回地址[start,end)中的最大的那个值的地址(迭代器),传入参数为两个地址或迭代器。
- 时间复杂度为O(n),n为数组大小
- 返回值是具体的数字,而不是一个地址
#include<bits/stdc++.h>
using namespace std;