c++ sort()函数用法

我在网上找了一些stl的sort函数的用法,有些用法怎么不能实现,请高手介绍一下sort的用法。
sort按降序排列如何实现?是 sort(A,1,'descend')吗?
如A是二维数组,如何实现按行排序,是sort(A,2),听说参数1是列排列,参数2是行排列。
上面两个我怎么不能通过编译啊?

使用sort()函数在做简单排序算法时候是非常好的方法。

sort(buffer,buffer+n,cmp); buffer为待排序数组的首地址,buffer+n为待排序数组的最后一个数据的地址。cmp为自定义的排序规则函数,可省略。

sort()函数默认是为升序排列,允许排序类型包括数值/字符/字符串。sort()也可以对结构体进行排序。

cmp函数的返回值为true和false或1和0,若为true/1,则sort()函数为升序排列,若为false/0,则sort()函数为降序排列。


下面为一个找出奶牛产奶量中间值的小程序,举例说明:

#include "iostream"
#include "algorithm"

using namespace std;

//奶牛结构类
typedef struct  
{
 int milk;
 int num;
}COW;

COW cow[100];
bool cmp(COW A, COW B);

//主函数
void main()
{
 
 int n;
 cout<<"请输入奶牛的数量:  ";
 cin>>n;
 for(int i=1;i<=n; i++)
 {
  cout<<"请输入奶牛"<<i<<"的产奶量:  ";
  cin>>cow[i-1].milk;
  cow[i-1].num = i;
 }
 sort(cow,cow+n,cmp); //排序比较
 cout<<"中间奶牛产奶量为:  "<<cow[n/2].milk<<endl;
 system("pause");
}

//cmp排序规则函数
bool cmp(COW A, COW B)
{
 if (A.milk < B.milk)  //按产奶量由小到大排序
 {
  return true;
 }
 else if (A.milk == B.milk)
 {
  if (A.num > B.num)  //产奶量相同时,按序号由大到小排序
  {
   return true;
  }
  return false;
 }
 else
 {
  return false;
 }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-07-22
察看msdn的帮助阿
sort
template<class RanIt>
void sort(RanIt first, RanIt last);
template<class RanIt, class Pred>
void sort(RanIt first, RanIt last, Pred pr);
The first template function reorders the sequence designated by iterators in the range [first, last) to form a sequence ordered by operator<. Thus, the elements are sorted in ascending order.

The function evaluates the ordering predicate X < Y at most ceil((last - first) * log(last - first)) times.

The second template function behaves the same, except that it replaces operator<(X, Y) with pr(X, Y).
第2个回答  推荐于2017-10-09
#include <algorithm>
void sort( iterator start, iterator end );
void sort( iterator start, iterator end, StrictWeakOrdering cmp );本回答被提问者采纳
第3个回答  2008-07-22
报什么错??
相似回答