题目:
algorithm头文件下的函数
分析:
1.max,min,abs,注意浮点型要用cmath下的fabs
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
//浮点型的绝对值
int main() {
double a = -4.3, b = -109.876;
printf("%.2lf %.2lf", fabs(a), fabs(b));
return 0;
}
- swap,reverse,(数组:reverse(a,a+2);
- 容器:reveser(v.begin()+2,v.begin()+4);
- next_permutation():求给定序列在全排列中的下一个序列
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
//next_permutation(arr,arr+3)求arr[0]到arr[2]之间的序列在全排列中的下一个序列
int main() {
int arr[10] = { 1,2,3 };
do
{
printf("%d%d%d\n", arr[0], arr[1], arr[2]);
} while (next_permutation(arr,arr+3));
return 0;
}
- fill():将数组或者容器的某段区间赋给某个相同的值
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int arr[10] = { 1,2,3,9,10,13 };
vector<int> v(8);
//数组
fill(arr, arr + 3, 0);
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
//容器
fill(v.begin() + 1, v.begin() + 5, 90);
for (int x : v) {
printf("%d ", x);
}
return 0;
}
- sort:主要是二级排序,和字符串长度排序
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct node {
int x, y;
}ssd[10];
bool cmp(node a, node b) {
if (a.x!=b.x) {
return a.x > b.x;
}
else {
return a.y > b.y;
}
}
int main() {
ssd[0].x = 2;
ssd[0].y = 2;
ssd[1].x = 9;
ssd[1].y = 10;
ssd[2].x = 2;
ssd[2].y = 1;
//排序
sort(ssd, ssd + 3, cmp);
for (int i = 0; i < 3; i++) {
printf("%d %d\n", ssd[i].x, ssd[i].y);
}
return 0;
}
结果:
9 10
2 2
2 1
字符串长度的排序:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
bool cmp(const string str1, const string str2) {
return str1.length() > str2.length();
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string str[3] = { "abcde","aa","bbb" };
sort(str, str + 3, cmp);
for (int i = 0; i < 3; i++) {
cout << str[i] << endl;
}
return 0;
}
浮点数的排序:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
bool cmp(double a,double b) {
return a>b;
}
int main() {
double arr[5] = { -3.9,-3.91,4.5,4.5004,10.01 };
sort(arr, arr + 5,cmp);
for (int i = 0; i < 5; i++) {
printf("%.4lf ", arr[i]);
}
return 0;
}
- lower_bound()和upper_bound()
lower_bound(first,last,val);
找first,last区间内第一个大于等于val的数,如果是数组,返回该位置的指针;如果是容器,返回该位置的迭代器。
upper_bound(first,last,val);
找first,last区间内第一个大于val的数,如果是数组,返回该位置的指针;如果是容器,返回该位置的迭代器。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int main() {
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int *lowpos = lower_bound(arr, arr + 5, 2);
printf("%d\n", *lowpos); //返回值
printf("%d\n", lowpos-arr); //返回下标
//寻找3,返回数组下标
printf("%d, %d\n", lower_bound(arr, arr + 10, 9) - arr, upper_bound(arr, arr + 10, 9) - arr);
return 0;
}