首页 > 代码库 > std::sort()
std::sort()
1 #include "stdafx.h" 2 #include <vector> 3 #include <algorithm> 4 #include <functional> 5 #include <iostream> 6 7 using namespace std; 8 9 //Return whether first element is greater than the second 10 bool UDgreater(int elem1,int elem2) 11 { 12 return elem1 > elem2; 13 } 14 class Csort 15 { 16 public: 17 //Return whether first element is less than the second 18 bool operator () (int a,int b) const 19 { 20 return a<b; 21 }; 22 }; 23 24 int _tmain(int argc, _TCHAR* argv[]) 25 { 26 vector<int> v1; 27 vector<int> ::iterator Iter1; 28 int arr[12]; 29 int i; 30 for (i = 0;i<=5;i++) 31 { 32 v1.push_back(2*i); 33 arr[i]= 2*i; 34 } 35 for (i = 6;i<=11;i++) 36 { 37 arr[i] = 23 - 2*i; 38 } 39 40 int ii; 41 for (ii = 0; ii<=5;ii++) 42 { 43 v1.push_back(2 * ii + 1); 44 } 45 cout <<"Original vector v1 = ("; 46 for(Iter1 = v1.begin();Iter1 != v1.end();Iter1++) 47 cout << *Iter1<<","; 48 cout<<")"<< endl; 49 cout <<"Original array arr = ("; 50 for (int n = 0;n<12;n++) 51 cout << arr[n]<<","; 52 cout << ")"<< endl; 53 54 //std::sort 默认排序方式 55 sort(v1.begin(),v1.end()); 56 cout<<"Sorted vector v1 = ("; 57 for(Iter1 = v1.begin();Iter1 != v1.end();Iter1++) 58 cout << *Iter1 <<","; 59 cout<<")"<<endl; 60 61 62 //使用自定义函数给数组排序,第三个参数为函数指针UDgreater 63 //第二个自定义参数为数据最大地址的后一位指针&arr[12]; 64 sort(&arr[0],&arr[12],UDgreater); 65 66 cout<<"Resorted(UDgreater) array arr = ("; 67 for(int n =0;n<12;n++) 68 cout << arr[n]<<","; 69 cout << ")"<<endl; 70 71 //使用<functional>库中 greater<int>()给向量v1排序; 72 sort(v1.begin(),v1.end(),greater<int>()); 73 //sort(v1.begin(),v1.end().Csort()); 74 75 cout << "Resorted (greater) vector v1 = ("; 76 for(Iter1 = v1.begin();Iter1 != v1.end();Iter1++) 77 cout << *Iter1 <<","; 78 cout << ")" << endl; 79 80 //A user - defined (UD) binary predicate can also be used 81 //sort (v1.begin(),v1.end(),UDgreater); 82 sort(v1.begin(),v1.end(),Csort()); 83 cout << "Resorted (Csort) vector v1 = ("; 84 for(Iter1 = v1.begin();Iter1!= v1.end();Iter1++) 85 cout << *Iter1 << ","; 86 cout << ")" <<endl; 87 88 system("Pause"); 89 //getchar(); 90 return 0; 91 }
std::sort(vec.begin(),vec.end(),Func);error C2780: “void std::sort(_RanIt,_RanIt)”: 应输入 2 个参数,却提供了 3 个解决方案:Func是一个class的成员函数,在class其定义处将其改为静态函数即可。 如 static bool Func(const Type& t1,const Type& t2);
std::sort()
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。