max(x, y):返回x和y中的最大值 min(x, y):返回x和y中的最小值 参数必须是两个,可以是浮点数 返回三个数:max(x, max(y, z)) abs(x):返回x的绝对值
#include <stdio.h> #include <algorithm> using namespace std; int main() { int x = 1, y = -2; printf("%d %d\n", max(x, y), min(x, y)); printf("%d %d\n", abs(x), abs(y)); return 0; } 1 -2 1 2swap(x, y)用来交换x和y的值
#include <stdio.h> #include <algorithm> using namespace std; int main() { int x = 1, y = -2; swap(x, y); printf("%d %d\n", x, y); return 0; } -2 1reverse(it, it2)将数组指针在[it, it2)之间的元素或容器的迭代器在[it, it2)范围内的元素进行反转
#include <stdio.h> #include <algorithm> using namespace std; int main() { int a[10] = {10, 11, 12, 13, 14, 15}; reverse(a, a + 4); // 将a[0]~a[3]反转 for(int i = 0; i < 6; i++) { printf("%d", a[i]); } return 0; } 13 12 11 10 14 15如果对容器中的元素(string) 进行反转,结果也是一样
#include <stdio.h> #include <algorithm> #include <string> using namespace std; int main() { string str = "abcdefghi"; reverse(str.begin() + 2, str.begin() + 6); // 对str[2]~str[5]反转 for(int i = 0; i < str.length(); i++) { printf("%c", str[i]); } return 0; } 13 12 11 10 14 15next_permutation()给出一个序列在全排列中的下一个序列
#include <stdio.h> #include <algorithm> using namespace std; int main() { int a[10] = {1, 2, 3}; //a[0]~a[2]之间的序列需要求解next_permutation do{ printf("%d%d%d\n", a[0], a[1], a[2]); }while (next_permutation(a, a + 3)); return 0; } 123 132 213 231 312 321fill()可以把数组或容器的某一段区间赋为某个相同的值,
#include <stdio.h> #include <algorithm> using namespace std; int main() { int a[5] = {1, 2, 3, 4, 5}; fill(a, a + 5, 233); for(int i = 0; i < 5; i++) { printf("%d", a[i]); } return 0; } 233 233 233 233 233lower_bound(first, last, val):用来寻找在数组或容器的[first, last)范围内第一个值大于等于val的元素的位置 upper_bound(first, last, val):用来寻找在数组或容器的[first, last)范围内第一个值大于val的元素的位置
#include <stdio.h> #include <algorithm> using namespace std; int main() { int a[10] = {1, 2, 2, 3, 3, 3, 5, 5, 5, 5}; //寻找-1 int *lowerPos = lower_bound(a, a + 10, -1); int *upperPos = upper_bound(a, a + 10, -1); printf("%d, %d\n", lowerPos - a, upperPos - a); //寻找1 lowerPos = lower_bound(a, a + 10, 1); upperPos = lower_bound(a, a + 10, 1); printf("%d, %d\n", lowerPos - a, upperPos -a); //寻找3 lowerPos = lower_bound(a, a + 10, 3); upperPos = upper_bound(a, a + 10, 3); printf("%d, %d\n", lowerPos - a, upperPos - a); //寻找4 lowerPos = lower_bound(a, a + 10, 4); upperPos = upper_bound(a, a + 10, 4); printf("%d, %d\n", lowerPos - a, upperPos - a); //寻找6 lowerPos = lower_bound(a, a + 10, 6); upperPos = upper_bound(a, a + 10, 6); printf("%d, %d\n", lowerPos - a, upperPos - a); return 0; } 0, 0 0, 0 3, 6 6, 6 10, 10如果只想获得欲查元素的下标,就可以不使用临时指针,而直接令返回值减去数组首地址即可
#include <stdio.h> #include <algorithm> using namespace std; int main() { int a[10] = {1, 2, 2, 3, 3, 3, 5, 5, 5, 5}; //注意数组下标从0开始 //寻找3 printf("%d, %d\n", lower_bound(a, a + 10, 3) - a, upper_bound(a, a + 10, 3) - a); return 0; 3 6