您的位置:首页 > 其它

STL中实现降序排列

2015-05-06 10:49 253 查看
#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都要定义比较函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: