利用c++11tuple实现多级排序

最近在做存储过程改造为内存数据库的服务的过程中,遇到了很多需要进行排序的地方,而利用sql语言本身的特性,可以很方便的对数据库查找出来的数据进行排序,而在使用c++语言进行改造的过程中,每次需要进行排序的地方,使用lambda或者函数对象去实现相应的功能,对于存储中只针对少许字段进行排序时,还可以很方便的实现,但是当涉及到字段很多时,需要写很多的逻辑判断,而且代码的阅读性很差,因此,想着有没有什么办法能够很方便的对基本的数据类型一次性完成排序,或者能够实现一个通用的接口,完成排序的功能。刚开始想到的是利用c++11提供的新特性,不定参数模板来实现多级排序的功能,后来还是放弃了这个想法。也许是自己对其不够了解,发现这种方法自己没有想出来,后来了解到c++11中的tuple功能,于是很方便的解决了这个问题。
class student
{
public:
	student():age(0), score(0), height(0)
	{
		memset(name, 0, sizeof(name));
	}
public:
	int age;
	int score;
	double height;
	char name[64];
};

struct compare
{
	bool operator() (const student* __x, const student* __y)
	{
		std::tuple<int, int, double, std::string> t1;
		std::tuple<int, int, double, std::string> t2;

		t1 = std::make_tuple(__x->age, __x->score, __x->height, __x->name);
		t2 = std::make_tuple(__y->age, __y->score, __y->height, __y->name);

		if (t1 < t2)
			return true;
		else
			return false;

	}
};

int main(int argc, char* argv[])
{
	student s1;
	s1.age = 12;
	s1.score = 88;
	s1.height = 54.5;
	strcpy_s(s1.name, "python");

	student s2;
	s2.age = 12;
	s2.score = 88;
	s2.height = 54.5;
	strcpy_s(s2.name, "hello");

	student s3;
	s3.age = 13;
	s3.score = 87;
	s3.height = 54.5;
	strcpy_s(s3.name, "python");

	std::vector<student*> vec;
	vec.push_back(&s1);
	vec.push_back(&s2);
	vec.push_back(&s3);

	std::sort(vec.begin(), vec.end(), compare());

	for(auto record : vec)
	{
		cout << "age" << record->age << "score" << record->score << "height" << record->height << "name" << record->name << endl;
	}

	system("pause");
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值