一、排序 sort
sort(first_pointer,first_pointer+n,cmp)
默认为升序
若要使用降序,自行写cmp 函数
bool cmp(int a,int b)
{
return a<b; //升序排列,如果改为return a>b,则为降序
}
例如:
方法一:定义比较函数(最常用)
//情况一:数组排列
int A[100];
bool cmp1(int a,int b)//int为数组数据类型
{
return a>b;//降序排列
//return a<b;//默认的升序排列
}
sort(A,A+100,cmp1);
//情况二:结构体排序
Student Stu[100];
bool cmp2(Student a,Student b)
{
return a.id>b.id;//按照学号降序排列
//return a.id<b.id;//按照学号升序排列
}
sort(Stu,Stu+100,cmp2);
注:比较方法也可以放在结构体中或类中定义。
//实现对map按value进行排序
map中含两个值分别为key和value,map是按照key值进行排序的,若value值进行排序,如下:
typedef pair<string, int> PAIR;
int cmp(const PAIR & x, const PAIR & y)
{
return x.second > y.second;
}
map<string,int> m;
vector<PAIR> vec;
for (map<wstring,int>::iterator curr = m.begin(); curr != m.end(); ++curr)
{
vec.push_back(make_pair(curr->first, curr->second));
}
sort(vec.begin(), vec.end(), cmp);
将map的key和value组成一个新的结构PAIR,一个PAIR型的vector存储map中的所有内容,对vecor按照value值进行排序。按顺序输出key:
注意:如果是类的话,这个cmp的定义要放在类的外面,作为非成员函数 或者定义成 static 成员函数(推荐),不然编译会出错(如图)。
正确写法:
将cmp定义为类的static 成员函数
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
string s;
getline(cin,s);
sort(s.begin(),s.end());
do
{
cout<<s<<endl;
}while(next_permutation(s.begin(),s.end()));
return 0;
}
注: next_permutation 原型:
#include <algorithm>
bool next_permutation(iterator start,iterator end)
注意:使用之前需要对所求全排列的数组进行升序排序。(因为它是基于当前数组去求下一个全排列)
原文:https://www.cnblogs.com/sunshine1218/p/12088728.html