万能头文件
目录
lower_bound(大于等于)和upper_bound(大于)
max min min_element max_element
#include <bits/stdc++.h>
取消数据流
数据量较大时
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
浮点数
精确到小数点后三位
float x = 3.1415926;
cout << fixed << setprecision(3) << x;
大小写转换
islower(ch1);
isupper(ch2);
char ch3=tolower(ch2);
char ch5=ch2-'A'+'a';
char ch4=toupper(ch1);
#include <bits/stdc++.h>
using namespace std;
char converted(char ch) {
if (islower(ch)) ch = toupper(ch);
else if (isupper(ch)) ch = tolower(ch);
return ch;
}
int main() {
string s;
getline(cin, s);
for (auto& i : s) {
i = converted(i);
}
cout << s << "\n";
return 0;
}
排序函数
1.范围是[st,end)
2.第三个参数默认是升序
sort(st,end)
二分查找
binary_search(,,)
1.可以用向量代替数组
2.binary_search() 只能用于单调的数据,返回值是布尔类型
3.三个参数
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> numbers = { 1,3,5,7,9 };
int target = 5;
bool found = binary_search(numbers.begin(), numbers.end(), target);
if (found) cout << "found";
else cout << "not found";
return 0;
}
lower_bound(大于等于)和upper_bound(大于)
1.不一定要先排序 只要是非降序的就行
2.数组的变量名直接代表数组的首地址,而容器则提供 data()
或 begin()
函数来获取首元素的地址。
3.lower_bound(st,end,x) 范围是[st,end) 不存在则返回的是end
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v= {5, 1, 7, 3, 10, 18, 9};
cout << v[1];
sort(v.begin(), v.end());
for (auto& i : v) {
cout << i << ' ';
}
cout << "\n";
//找到数组中第一个大于等于8的位置 下标
cout << (lower_bound(v.begin(), v.end(), 8) - v.begin()) << "\n";
}
其他库函数
两个数据的交换 swap()
int a = 10;
int b = 9;
swap(a, b);
数据的反转reverse() 前闭后开
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> vec = { 1,2,3,4,5 };
reverse(vec.begin(), vec.end());
for (int num : vec) {
cout << num;
}
}
unique
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[] = { 1,1,2,3,4 };
int n = unique(a, a + 5) - a;
for (int i = 0; i < n; ++i) cout << a[i] << " ";
return 0;
}
全排列
要枚举数组的所有情况
#include <bits/stdc++.h>
using namespace std;
int a[10];
int main() {
for (int i = 1; i <= 4; i++) a[i] = i;
bool tag = true;
while (tag)
{
for (int j = 1; j <= 4; j++) cout << a[j] << " ";
cout << "\n";
tag = next_permutation(a + 1, a + 1 + 4);
}
return 0;
}
最值查找
max min min_element max_element
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[2] = { 1,2 };
vector<int> vec = { 1,2 };
min(1, 2);
min({ 1,2,3,4 });
//min(a10);
int minel = *min_element(a, a + 1 +1);
int maxel = *max_element(a, a + 1+1);
int minelvec = *min_element(vec.begin(), vec.end());
int maxelvec = *max_element(vec.begin(), vec.end());
cout << minel << maxel << minelvec << maxelvec;
}