对自定义对象进行排序(C++/Java)

本文探讨如何在C++和Java中对自定义对象进行排序,重点介绍了在各自语言环境下按照对象内特定属性进行排序的方法。
摘要由CSDN通过智能技术生成

自定义了对象,如何按照自定对象中某一或多个元素对其进行排序呢?以下分别从C++和java对其进行实现。

一:C++

/*
实现对自定义的对象类型进行排序(按照其中的元素),首先将对象存放在vector中,然后利用algorithm库函数中的sort对其进行排序,需要重写排序函数以函数名
作为函数指针作为sort的第三个参数
*/

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;


struct students{
	int age;
	string name;
};

void addStudents(vector<students> &vec, int age, string name){
	students stu;
	stu.age = age;
	stu.name = name;
	vec.push_back(stu);
	
}

// 按照年龄进行排序 升序
bool sortByAge(const students &s1, const students &s2){
	return s1.age < s2.age;
}


// 先按照年龄进行排序 年纪一样 按照姓名排序
bool sortByAll(const students &s1, const students &s2){
	if(s1.age < s2.age) return true;
	else if(s1.age > s2.age) return false;
	else return s1.name < s2.name;
}
int main(){
	vector<s
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值