【c++进阶:c++ algorithm的常用函数】

c++ algorithm的常用函数

https://blog.csdn.net/hy971216/article/details/80056933

reverse()

reverse(it,it2) 可以将数组指针在[it,it2)之间的元素或容器的迭代器在[it,it2)范围内的元素进行反转。

返回全排列:next_permutation(a,a+3)返回两个位置之间的全排列并原地赋值;

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 int main(){
 5     int a[3]={1,2,3};
 6     printf("%d %d %d
",a[0],a[1],a[2]);
 7     while(next_permutation(a,a+3)){
 8         printf("%d %d %d
",a[0],a[1],a[2]);
 9     }
10     return 0;
11 }

 返回两个位置之间的某个数第一次出现的下标和最后一次的下标:

 1 #include<stdio.h>
 2 #include<string>
 3 #include<vector>
 4 #include<algorithm>
 5 using namespace std;
 6 int main()
 7 {
 8     int a[10]={1,2,2,3,3,3,5,5,5,5};
 9     printf("%d,%d
",int(lower_bound(a,a+10,3)-a),int(upper_bound(a,a+10,3)-a));
10     return 0;
11 }

 sort()函数的排序:可以对数组元素和结构体数组排序; 对容器排序只能对vector, string,  deque进行sort()

deque是一种双头容器,参见:https://www.cnblogs.com/LearningTheLoad/p/7450948.html

 1 #include<stdio.h>
 2 #include<string>
 3 #include<vector>
 4 #include<algorithm>
 5 using namespace std;
 6 bool cmp(int a,int b){
 7     return a>b;
 8 }
 9 int main()
10 {
11     vector<int> vi;
12     vi.push_back(3);
13     vi.push_back(1);
14     vi.push_back(2);
15     sort(vi.begin(),vi.end(),cmp);
16     for(int i=0;i<3;i++){
17         printf("%d ",vi[i]);
18     }
19     return 0;
20 }
原文地址:https://www.cnblogs.com/joelwang/p/10518413.html