algorithm头文件下的常用函数
- max(x,y),min(x,y),abs(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));
system("pause");
return 0;
}
- reverse(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);
for (int i = 0; i < 6; i++)
printf("%d ", a[i]);
system("pause");
return 0;
}
- next_permutaion(a,a+3),给出一个序列在全排列中的下一个序列
#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));
system("pause");
return 0;
}
输出结果:
123
132
213
231
312
321
- file(a,a+4,233),把数组或容器中的某一段区间赋为某个相同的值。
#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]);
system("pause");
return 0;
}
5.sort(a,a+4),默认按从小到大的顺序排序
#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
int a[5] = { 3, 1, 4, 2 };
sort(a, a + 4);
for (int i = 0; i < 4; i++)
printf("%d ", a[i]);
system("pause");
return 0;
}
如果想要从大到小来排序,则要使用比较函数cmp来告诉sort何时要交换元素
char型数组从大到小排列:
#include <stdio.h>
#include <algorithm>
using namespace std;
bool cmp(char a, char b)
{
return a > b;//> 左大右小
}
int main()
{
char c[] = { 'T', 'W', 'A', 'K' };
sort(c, c + 4, cmp);
for (int i = 0; i < 4; i++)
printf("%c", c[i]);
system("pause");
return 0;
}
输出结果:
WTKA
结构体数组的排序:
#include <stdio.h>
#include <algorithm>
using namespace std;
struct node{
int x, y;
}ssd[10];
bool cmp(node a, node b){
return a.x > b.x;//按x值从大到小对结构体数组排序
}
int main()
{
ssd[0].x = 2;
ssd[0].y = 2;
ssd[1].x = 1;
ssd[1].y = 3;
ssd[2].x = 3;
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);
system("pause");
return 0;
}
输出结果:
3 1
2 2
1 3
而如果想先按x从小到大排序,但当x相等的情况下,按照y的大小从小到大来排序(即进行二级排序),那么cmp的写法是:
bool cmp(node a, node b){
if (a.x != b.y) return a.x > b.x;
else return a.y < b.y;
}
容器的排序:
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a, int b){
return a > b;
}
int main()
{
vector<int> vi;
vi.push_back(3);
vi.push_back(1);
vi.push_back(2);
sort(vi.begin(), vi.end(), cmp);//对整个vector进行排序
for (int i = 0; i < 3; i++)
printf("%d ", vi[i]);
system("pause");
return 0;
}
string的排序:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str[3] = { "bbbb", "cc", "aaa" };
sort(str, str + 3);
for (int i = 0; i < 3; i++)
cout << str[i] << endl;
system("pause");
return 0;
}
输出结果:
aaa
bbbb
cc