A sort sort
sort (first_pointer, first_pointer + n,
cmp) default ascending
To use the descending, self-write function cmp
CMP BOOL (A int, int B)
{
return A <B; // ascending order, if instead return a> b, in descending order was
}
For example:
Method a: comparison function defined (most common)
// a case where: the array arrangement
int A [100];
BOOL CMP1 (A int, int B) // int type array data
{
return A> B; // descending arrangement
// return a <b; // default ascending order
}
Sort (a, a + 100, CMP1);
@ Case 2: ordered structure
Student Stu [100];
BOOL CMP2 (Student A, Student B)
{
return a.id> b.id; // student number in descending order
// return a.id <b.id ; // student number in ascending order
}
Sort (Stu, Stu + 100, CMP2);
Note: comparison of methods may be placed within the structure or class definitions.
// map to achieve sorted by value
map containing values of two key and value, are sorted according to the map key value, value if the values are sorted as follows:
typedef pair <String, int> the PAIR;
int CMP ( the PAIR X & const, Y & const the PAIR)
{
return x.second> y.second;
}
Map <String, int> m;
Vector <the PAIR> VEC;
for (Map <wstring, int> :: = m Iterator Curr. the begin ();! Curr m.end = (); Curr ++)
{
vec.push_back (the make_pair (curr-> First, curr-> SECOND));
}
Sort (vec.begin (), vec.end () , CMP);
the key and value map of a new structure consisting pAIR, all the contents of a memory map pAIR type of vector, sorted according to the value vecor value. Sequentially output key:
Note: If you are that kind of thing, this cmp definition should be placed outside the class, or as a non-member function defined as static member function (recommended), or else the compiler will go wrong (as shown).
Correct wording:
The cmp defined as class static member function
#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)
Note: the need for perfection arranged in ascending order of the array prior to use. (Because it is based on current array to seek the next full array)