【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\n",a[0],a[1],a[2]);
 7     while(next_permutation(a,a+3)){
 8         printf("%d %d %d\n",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\n",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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM