std::sort() 如何自定义比较函数 进行排序 。

本文介绍如何使用C++标准库中的std::sort()函数通过自定义比较函数实现对结构体数组的升序和降序排列。示例代码展示了如何定义比较函数以及如何将这些函数应用于std::sort()来对包含年龄和姓名字段的结构体数组进行排序。

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

/*

std::sort() 如何自定义比较函数 进行排序 。

Parameters
first, last	-	the range of elements to sort
policy	-	the execution policy to use. See execution policy for details.
comp	-	comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second. 
The signature of the comparison function should be equivalent to the following:

//比较函数定义规则如下
bool cmp(const Type1 &a, const Type2 &b);

The signature does not need to have const &, but the function object must not modify the objects passed to it.
The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them. ​


*/

#include "stdafx.h"
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace  std;

struct STest
{
	int m_age;
	std::string m_strName;
};

typedef std::vector<STest>CVector;

//升序
bool compareAsc(const STest &value1,const STest &value2)
{
	return value1.m_age > value2.m_age;
}

//降序
bool compareDes(const STest &value1,const STest &value2)
{
	return value1.m_age < value2.m_age;
}


int _tmain(int argc, _TCHAR* argv[])
{
	std::cout<<"原始数据\n";
	CVector vecTest;
	for (int i = 0; i < 10; i++)
	{
		STest tmp;
		tmp.m_age = i;
		char ch[260]={0};
		sprintf(ch,"%dhello",i);
		tmp.m_strName = std::string(ch);
		vecTest.push_back(tmp);
		std::cout<<"age: "<<tmp.m_age <<"\tname: "<<tmp.m_strName.c_str()<<endl;
	}

	std::cout<<"==============================\n";
	std::cout<<"升序序排序\n";
	std::sort(vecTest.begin(),vecTest.end(),compareAsc);
	CVector::iterator iter = vecTest.begin();
	for (iter; iter != vecTest.end(); iter++)
	{
		std::cout<<"age: "<<iter->m_age <<"\tname: "<<iter->m_strName.c_str()<<endl;
	}

	std::cout<<"==============================\n";
	std::cout<<"降序排序\n";
	std::sort(vecTest.begin(),vecTest.end(),compareDes);
	iter = vecTest.begin();
	for (iter; iter != vecTest.end(); iter++)
	{
		std::cout<<"age: "<<iter->m_age <<"\tname: "<<iter->m_strName.c_str()<<endl;
	}
	return 0;
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值