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都要定义比较函数
相关文章推荐
- STL中list实现降序排列
- Excel第一行的下拉三角形如何实现? 升序、降序排列
- stl实现全排列模板
- 请通过代码实现以下功能:输入一个5X5的二维数组,将数组进行排序,其中一维数组按照平均值降序,一维数组内部升序排列。
- JS实现数组按升序及降序排列的方法
- 全排列及其STL实现
- 排列组合计算第m种组合 STL实现——pku1833
- 实现 DataGird 的升序和降序排列
- 数组中有4个元素(@”cc”,@”dd”,@”tt”,@”ff”),使用数组中的block方法实现降序排列
- 使用MorphiaQuery实现降序排列
- 随机产生50个30到35的整数,统计每个数字出现的次数(TreeMap实现),输出时按照数字的降序排列,并且统计出现次数最多的数字和它的次数。
- 算法学习——搜索和C++ STL 实现全排列和去重全排列
- 全排列的STL实现
- 入门经典 第七章 7.2.4 生成的排列,STL实现
- stl next_permutation的全排列原理及实现样例
- 全排列问题的递归、STL实现
- 全排列算法之STL实现
- 在WordCount基础上改进,实现以词频为键值,并按词频降序排列
- 全排列算法递归及STL实现,八皇后问题
- 求全排列问题--- java实现