sort函数的用法及范例(亲测好用)

来源:互联网 发布:我的世界手机版女仆js 编辑:程序博客网 时间:2024/04/30 15:00

MSDN中的定义:

template<class RanIt>
void sort(RanIt first, RanIt last); (1)
template<class RanIt, class Pred>
void sort(RanIt first, RanIt last, Pred pr); ( 2)


头文件:
#include <algorithm>
using namespace std;

1.默认的sort函数是按升序排。对应于(1)
sort(a,a+n);   //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。对应于(2)
例如:
int cmp( const int &a, const int &b ){
    if( a > b )
       return 1;
    else
       return 0;
}
sort(a,a+n,cmp);
是对数组a降序排序
又如:
int cmp( const POINT &a, const POINT &b ){
    if( a.x < b.x )
       return 1;
    else
       if( a.x == b.x ){
          if( a.y < b.y )
             return 1;
          else
             return 0;
        }
       else
          return 0;
}
sort(a,a+n,cmp);
是先按x升序排序,若x值相等则按y升序排


其他相关的知识 其他高手都解释的很清楚了 这里我就给出一个具体例子作为参考:


#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <algorithm>
#include <iostream>
//题目要求:文件排序,先按文件类型进行排序,如果相同再按文件名进行排序
using namespace std;


struct node 
{
string a, b;  //a代表文件名,b代表文件类型
};


bool lt(string x, string y)
{
int i;
for(i = 0; i < x.length(); i++)
{
if(x[i] >= 'A' && x[i] <= 'Z')
x[i] = 'a' + (x[i] - 'A');  //转换成小写
}


for(i = 0; i < y.length(); i++)
{
if(y[i] >= 'A' && y[i] <= 'Z')
y[i] = 'a' + (y[i] - 'A');
}


return x < y;
}


bool comp(node x, node y)
{
if(x.b != y.b)
return x.b < y.b;
else
return lt(x.a, y.a);
}


int main()
{
node arr[1000];
char stra[256] = {0};
char strb[256] = {0};
int size = 6;
for(int i = 0; i < size ; i++)
{
scanf("%s%s", stra, strb);
arr[i].a = (string)stra;
arr[i].b = (string)strb;
}
sort(arr, arr + size, comp);
for(int j = 0; j < size; j++)
cout<<arr[j].a<<"."<<arr[j].b<<endl;
return 0;
}


原创粉丝点击