STL第九部分algorithm
✨1、algorithm【常用算法函数】
① 头文件
#include <algorithm>
①、sort()
具有和快排一样的速度
时间复杂度
bool cmp(int a ,int b)
{
return a > b ;
}
int list1[5] = {5, 14, 3, 4, 2};
vector<int> list2(list1, list1 + 5);
sort(list1, list1 + 5); // 从小到大
sort(list2.begin(), list2.end(), cmp); // 从大到小
std::cout << "list1排序后:" << endl;
for (auto i: list1){
std::cout << i << " ";
}
std::cout << endl;
std::cout << "list2排序后:" << endl;
for (auto i: list2){
std::cout << i << " ";
}
std::cout << endl;
② __gcd 最大公约数
// 最大公约数
std::cout << "20与4的最大公约数:" << __gcd(20, 4) << endl; // 4
③ max min最值
// 求最值
std::cout << "最大值:" << max(1,8) << endl; // 8
std::cout << "最小值:" << min(6,7) << endl; // 6
④ swap 交换
// 交换
int a = 5, b = 7;
std::cout << "交换前a:" << a << "\t" << "b:" << b << endl;
swap(a,b);
std::cout << "交换后a:" << a << "\t" << "b:" << b << endl;
⑤ lower_bound()与upper_bound() 【二分查找】
时间复杂度
使用方式(第⑤部分 核心函数)
①至⑤运行截图
附全文代码
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool cmp(int a ,int b)
{
return a > b ;
}
int main(){
// sort() 函数
int list1[5] = {5, 14, 3, 4, 2};
vector<int> list2(list1, list1 + 5);
sort(list1, list1 + 5); // 从小到大
sort(list2.begin(), list2.end(), cmp); // 从大到小
std::cout << "list1排序后:" << endl;
for (auto i: list1){
std::cout << i << " ";
}
std::cout << endl;
std::cout << "list2排序后:" << endl;
for (auto i: list2){
std::cout << i << " ";
}
std::cout << endl;
// 最大公约数
std::cout << "20与4的最大公约数:" << __gcd(20, 4) << endl;
// 求最值
std::cout << "最大值:" << max(1,8) << endl;
std::cout << "最小值:" << min(6,7) << endl;
// 交换
int a = 5, b = 7;
std::cout << "交换前a:" << a << "\t" << "b:" << b << endl;
swap(a,b);
std::cout << "交换后a:" << a << "\t" << "b:" << b << endl;
return 0;
}
### ```