STL库中sort函数用法

头文件为#include<algorithm> ,Sort函数有三个参数:

  • 第一个是要排序的数组的起始地址。
  • 第二个是结束地址(最后一位要排序的地址)
  • 第三个参数是排序的方法,可以从小到大也可以是从大到小,当不写第三个参数时默认的排序方法时从小到大排序。
     

升序和降序


int main()
{
    int a[10]={9,5,7,8,4,1,2,6,3,10};
    sort(a,a+10);//当最后一个参数不写的时候,默认为升序排序;
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";
}

//1  2 3 4 5 6  7 8 9 10;

降序的话有两种方式,第一是直接调用函数,C++标准库的强大功能完全可以解决这个问题。greater<数据类型>()  //降序排序

例如: sort(a,a+10,greater<int>());就是降序排序;还有就是直接写个cmp比较函数来完成:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a[10]={9,5,7,8,4,1,2,6,3,10};
    sort(a,a+10,greater<int>());//降序排序;
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";

}

// 10 9 8 7 6 5 4 3 2 1

写比较函数

bool cmp(int a,int b)
{
    return a>b;  //如果是return a<b 的话就是升序排序;
}

int main()
{
    int a[10]={9,5,7,8,4,1,2,6,3,10};
    sort(a,a+10,cmp);//降序排序;
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";
}

// 10 9 8 7 6 5 4 3 2 1

结构体变量的排序


using namespace std;

struct sdut
{
  int y;
}a[123461];

bool cmp(sdut a,sdut b)
{
    return a.y<b.y;//升序排列;a>b为降序排列;
}

int main()
{
    int m,n,t;
    while(cin>>t)
    {
        for(int i=0;i<t;i++)
            cin>>a[i].y;
        sort(a,a+t,cmp);
        for(int i=0;i<t;i++)
            cout<<a[i].y<<" "<<endl;
    }
}
class Student
 
{ 
public:
    Student(string name, int id) //构造函数 
    {
         m_name = name; 
        m_id = id; 
    }
 
    void printT() 
    { 
        cout << "name: " << m_name << " id " << m_id << endl; 
    }
 
public: 
    string m_name; 
    int m_id;
 
};
 
bool CompareS(Student &s1, Student &s2) //自定义的排序函数,顺序,必须是布尔型
 
{ 
    return (s1.m_id < s2.m_id); 
}
 
void main()
 
{
    Student s1("老大", 1); 
    Student s2("老二", 2); 
    Student s3("老三", 3);
    Student s4("老四", 4);
 
    vector<Student> v1;
    v1.push_back(s4); 
    v1.push_back(s1); 
    v1.push_back(s3); 
    v1.push_back(s2); 

    for (vector<Student>::iterator it = v1.begin(); it != v1.end(); it++) 
    {
        it->printT();
    }
 
    //sort 根据自定义函数对象 进行自定义数据类型的排序 
    cout << "-------------sort()后-------------"<< endl;
    sort(v1.begin(), v1.end(), CompareS); 
    for (vector<Student>::iterator it = v1.begin(); it != v1.end(); it++) 
    {
         it->printT(); 
    } 
}

https://blog.csdn.net/Africa_South/article/details/87905127

发布了142 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_30460949/article/details/102487205