STL vector按多字段值排序

上一篇我们讲到STL map的key如果由多个值组成,并按照这些值分别进行排序的情况。在最后的结论中我们说到“通常我们不用STL algorithm中的sort函数,来对一个map进行排序,而对vector的元素进行排序则可以很方面地使用sort函数。”

 

下面就是一个完整的,vector按多字段值进行排序的示例代码:

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

class Student
{
private:
	int id;			// 学号
	string name;		// 姓名
	float eyesight;		// 视力
	float height;		// 身高
	float chinese;		// 语文成绩
	float english;		// 英文成绩
	float math;		// 数学成绩
public:
	Student(int id, string name, float eyesight, float height, float chinese, float english, float math)
	{
		this->id = id;
		this->name = name;
		this->eyesight = eyesight;
		this->height = height;
		this->chinese = chinese;
		this->english = english;
		this->math = math;
	}

	int get_id()
	{
		return id;
	}

	string get_name()
	{
		return name;
	}

	float get_eyesight()
	{
		return eyesight;
	}

	float get_height()
	{
		return height;
	}

	float get_chinese()
	{
		return chinese;
	}

	float get_english()
	{
		return english;
	}

	float get_math()
	{
		return math;
	}
};

// 比较大小的函数(谓词)
bool comparer(Student& stu_a, Student& stu_b)
{
	// 按eyesight升序 + height升序排列
	if(stu_a.get_eyesight() != stu_b.get_eyesight())	
		return (stu_a.get_eyesight() < stu_b.get_eyesight());
	else
		return (stu_a.get_height() < stu_b.get_height());
	
	// 按eyesight降序° + height降序排列
	//if(stu_a.get_eyesight() != stu_b.get_eyesight())	
	//	return (stu_a.get_eyesight() > stu_b.get_eyesight());
	//else
	//	return (stu_a.get_height() > stu_b.get_height());

	// 按eyesight升序 + height降序排列
	//if(stu_a.get_eyesight() != stu_b.get_eyesight())	
	//	return (stu_a.get_eyesight() < stu_b.get_eyesight());
	//else
	//	return (stu_a.get_height() > stu_b.get_height());

	// 按eyesight降序 + height升序排列
	//if(stu_a.get_eyesight() != stu_b.get_eyesight())	
	//	return (stu_a.get_eyesight() > stu_b.get_eyesight());
	//else
	//	return (stu_a.get_height() < stu_b.get_height());
}

int main(int argc, char** argv)
{
	vector<Student> vec;
	vec.push_back(Student(4, "Dudley", 1.1f, 170.2f, 90.5f, 89.5f, 93.0));
	vec.push_back(Student(3, "Chris", 1.1f, 163.4f, 93.5f, 90.0f, 83.5f));
	vec.push_back(Student(2, "Bob", 1.5f, 166.6f, 86.0f, 98.5f, 85.0f));
	vec.push_back(Student(1, "Andrew", 1.5f, 173.2f, 98.5f, 100.0f, 100.f));

	// 调用STL中的sort函数,其中的第三个参数就是我们前面定义的,比较两个Student对象大小的函数
	sort(vec.begin(), vec.end(), comparer);

	vector<Student>::iterator iter;
	for(iter = vec.begin(); iter != vec.end(); ++iter)
	{
		cout << (*iter).get_eyesight() << "\t" << (*iter).get_height() << endl;
	}

	return 0;
}

输出的结果为:

1.1     163.4

1.1    170.2

1.5     166.6

1.5    173.2


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值