STL中实现降序排列

#include <iostream>
#include <algorithm>
#include <list>
#include <iterator>
using namespace std;

template <typename T>
void printList(const list<T> &listRef);

/*
template <class T>
bool cmp(T t1, T t2)
{
	return t1>t2;
}
*/

bool cmp(int t1, int t2)
{
	return t1>t2;
}

int main()
{
	const int SIZE = 4;
	int array[SIZE] = {2,6,4,8};
	list<int> values;
	list<int> otherValues;

	values.push_front(1);
	values.push_front(2);
	values.push_back(4);
	values.push_back(3);

	cout<<"\nvalues contains: ";
	printList(values);

	values.sort();
	cout<<"\nvalues after sorting contains: ";
	printList(values);

	otherValues.insert(otherValues.begin(),array,array+SIZE);
	cout<<"\nAfter insert, otherValues contains: ";
	printList(otherValues);

	values.splice(values.end(),otherValues);
	cout<<"\nAfter splice, values contains: ";
	printList(values);

	values.sort();
	cout<<"\nAfter sort, values contains: ";
	printList(values);

	//降序排列
	values.sort(cmp);
	cout<<"\nAfter sort, values contains: ";
	printList(values);

	return 0;
}

template <typename T>
void printList(const list<T> &listRef)
{
	if(listRef.empty())
		cout<<"List is empty";
	else
	{
		ostream_iterator<T> output(cout," ");
		copy(listRef.begin(),listRef.end(), output);
	}
}
执行结果

</pre><pre code_snippet_id="659886" snippet_file_name="blog_20150506_4_6145085" name="code" class="cpp">通过传递自定义函数cmp的函数指针可实现对list降序排序,但是对于cmp定义为标准模板函数会编译报错,求解决方法是不是需要对每个具体实现的list都要定义比较函数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值