C++中sort() 的使用方法----STL

本文详细介绍了C++中sort函数的基础用法与扩展应用,包括如何实现数组的升序与降序排列,以及如何对结构体按指定字段进行排序。此外,还提供了使用STL中的greater和less进行排序的方法,并展示了通过自定义比较类实现排序的例子。

头文件要求:#include <algorithm>

首先形式:sort(first_pointer,first_pointer+n,cmp);

前两个参数都是指针,最后一个cmp是比较的规则;cmp也可以是缺省的,因为这个时候默认的是按照升序排列来做的;

 基础用法:就是对前n个元素进行升序排列:

扩展用法:编写sort(...)中的cmp;可以对数组进行降序排序,同时也可以对结构体排序;

①:对数组降序排序:

#include "stdafx.h"  
#include <iostream>  
#include <set>  
#include <string>  
#include <algorithm>
using namespace std;
bool cmp1(int a, int b)
{
	return a > b;
}
int main()
{
	int a[] = { 1,5,4,6,7,8,9,10 };
	sort(a, a+8,cmp1);
	for (int i = 0; i < 10; i++) {
		cout << a[i] << endl;
	}
	return 0;
}

②对结构体中的某一个关键元素降序

#include "stdafx.h"  
#include <iostream>  
#include <set>  
#include <string>  
#include <algorithm>
using namespace std;
struct Student {
	int id;
	string name;
}stu[100];
bool cmp1(struct Student a,struct Student b)
{
	return a.id > b.id;
}
int main()
{
	stu[0].id = 123, stu[0].name = "asdasd";
	stu[1].id = 124, stu[1].name = "qqqqqq";
	stu[2].id = 125, stu[2].name = "wwwwww";
	sort(stu,stu+3,cmp1);
	for (int i = 0; i < 3; i++) {
		cout << stu[i].id <<" "<<stu[i].name<<endl;
	}
	return 0;
}

③还可以直接使用STL的方法进行简单的降序和升序排序,对于结构体是不适合的,加上头文件#include <functional>;

例如:

sort(stu,stu+3,greater<struct Student>());//不可以对结构体排序
sort(a,a+3,greater<int>());//对int数组进行降序排序
sort(a,a+3,less<int>());//对int数组进行升序排序

④声明比较类:

struct Less
{
    bool operator()(const Student& s1, const Student& s2)
    {
        return s1.id<s2.id; //升序排列
    }
};
sort(sutVector.begin(),stuVector.end(),Less());

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值