利用std::sort()函数实现自定义排序规则的排序算法

本文详细介绍了C++ STL中的sort函数用法,包括默认排序和自定义比较函数的使用,通过实例展示了如何对vector数组进行排序,以及如何定义和应用自定义比较函数对复杂数据类型进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

一. std::sort()函数

1. 默认方法

template <class RandomAccessIterator>
  void sort (RandomAccessIterator first, RandomAccessIterator last);

适用于自定义的vector数组,从小到大排序,比如:

vector<int> vec{20,34,1,34,14,7,9,40};
sort(vec.begin(),vec.end());
//或者
sort(vec.begin(), vec.begin() + 5);

2. 自定义比较函数

template <class RandomAccessIterator, class Compare>
  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

后面的comp就是自定义的比较函数

struct Compare{
    bool operator()(const pair<int,int> &p1,const pair<int,int> &p2)
    {
        return p1.second < p2.second;
    }
} comp_pair;

int main(int argc,char **argv)
{
	std::vector<pair<int,int>> v;
    srand((unsigned int)time(NULL));
    for(int i = 0;i < 10;i++){
        int r1 = rand() % 100;
        int r2 = rand() % 150;
        v.push_back({r1,r2});
    }
    for(auto it : v)
        cout << it.first << " " << it.second <<", ";
    cout << endl;
    std::sort(v.begin(),v.end(),comp_pair);
    for(auto it : v)
        cout << it.first << " " << it.second <<", ";
    cout << endl;  

	return 0;
}

也可以简单地定义一个bool函数

struct Coor
{
    int x;
    int y;
    Coor(int x_ , int y_){ x  = x_ ; y = y_ ; }
};
bool comp_coor(const Coor &c1,const Coor &c2){
    return c1.y < c2.y;
}

int main(int argc,char **argv)
{
	srand((unsigned int)time(NULL));

    std::vector<Coor> coors;
    for(int i = 0;i < 10;i++){
        int r1 = rand() % 100;
        int r2 = rand() % 150;
        Coor coor(r1,r2);
        coors.push_back(coor);
    }
    
    for(auto it : coors){
        cout << it.x << " " << it.y << " , ";
    }
    cout << endl;
    std::sort(coors.begin(),coors.end(),comp_coor);
    for(auto it : coors){
        cout << it.x << " " << it.y << " , ";
    }
    cout << endl;
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值