stl list自定义排序准则

list和vector默认的排序准则是升序排序,我们可以通过传递自定义参数的方式,指定他的排序准则。通常有两种指定方式:

(1)通过传递比较函数

(2)传递函数对象


/*************************************************************************
    > File Name: listSort.cpp
    > Author: ltf
    > Created Time: Thu 31 Mar 2016 11:46:31 AM CST
 ************************************************************************/

#include<iostream>
#include<list>

typedef struct 
{
	int x;
	int y;
}Node;
using namespace std;
//按Y降序,函数
bool sortFunction(const Node &v1,const Node &v2)
{
	if(v1.y > v2.y)
		return true;
	else
		return false;
}
//按Y升序,函数对象
struct sortObject{
	bool operator()(const Node &v1,const Node &v2) //重载函数操作符
	{
		if(v1.y < v2.y)
			return true;
		else
			return false;
	}
};

void print(list<Node> &test)
{
	for(const auto & elem:test)
	{
		cout << "x:" << elem.x << " y:" << elem.y << endl;
	}
}

int main(void)
{
	list<Node> test;
	Node tmp;
	for(int i=0;i<3;i++)
	{
		tmp.x = i;
		tmp.y = 3-i;
		test.push_back(tmp);
	}
	print(test);
	test.sort(sortObject()); //函数对象
	cout << "after sorted 1(Y ascending):" <<endl;
	print(test);
	test.sort(sortFunction); //传递函数指针
	cout << "after sorted 2(Y descending):" <<endl;
	print(test);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值