STL中list实现降序排列
来源:互联网 发布:软件实施顾问岗位职责 编辑:程序博客网 时间:2024/06/05 06:36
STL list可以对基本数据、字符串直接调用sort()函数默认做升序排列,但是对于降序排列或者对非基本数据类型排序(对象、数组等)需要借助operator()函数实现,这点和Java中的List很相似。
具体调用函数:
list.sort(Cmpare());
具体调用函数:
list.sort(Cmpare());
其中Cmpare是一个类或结构体,成员函数operator()必须是公共类型的。
我举一个简单的例子(对学生按年龄降序排列):
- #ifndef _STUDENT_H_
- #define _STUDENT_H_
- #include <string>
- using namespace std;
- class Student
- {
- private:
- int age;
- string name;
- public:
- void setAge(int age);
- void setName(string name);
- int getAge() const;
- string getName() const;
- };
- #endif
- #include "Student.h"
- void Student::setAge(int age)
- {
- this->age = age;
- }
- void Student::setName(string name)
- {
- this->name = name;
- }
- int Student::getAge() const
- {
- return this->age;
- }
- string Student::getName() const
- {
- return this->name;
- }
- #ifndef _CMPARE_H_
- #define _CMPARE_H_
- #include "Student.h"
- class Cmpare
- {
- public:
- bool operator()(const Student st1,const Student st2) const;
- };
- #endif
- #include "Cmpare.h"
- bool Cmpare::operator()(const Student st1,const Student st2) const
- {
- return st1.getAge() > st2.getAge();
- }
- #include "stdafx.h"
- #include <stdlib.h>
- #include <list>
- #include <iostream>
- #include "Cmpare.h"
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- Student stu1;
- stu1.setAge(20);
- stu1.setName("stu1");
- Student stu2;
- stu2.setAge(18);
- stu2.setName("stu2");
- Student stu3;
- stu3.setAge(17);
- stu3.setName("stu3");
- Student stu4;
- stu4.setAge(22);
- stu4.setName("stu4");
- list<Student> stuList;
- stuList.push_back(stu1);
- stuList.push_back(stu2);
- stuList.push_back(stu3);
- stuList.push_back(stu4);
- stuList.sort(Cmpare());
- list<Student>::iterator stuIter = stuList.begin();
- for( ; stuIter != stuList.end() ; stuIter ++)
- {
- cout<<"name:"<<(*stuIter).getName() <<",age:"<<(*stuIter).getAge()<<endl;
- }
- return 0;
- }
运行结果:
name:stu4,age:22
name:stu1,age:20
name:stu2,age:18
name:stu3,age:17
0 0
- STL中list实现降序排列
- STL中实现降序排列
- 使用MorphiaQuery实现降序排列
- List简单升序,降序排列 linq
- 降序排列
- 降序排列
- 冒泡排序实现升序和降序排列
- C++中set按降序排列方法。
- 实现List集合中数据逆序排列
- 实现List集合中数据逆序排列
- 对List的升序与降序排列函数sort()
- 对List的升序与降序排列函数sort()
- stl实现全排列
- c# OrderBy 实现List升序降序
- stl中list的sort算法实现
- C++中STL List排序实现
- STL 中list的sort函数实现
- STL中List的实现分析
- HibernateDaoSupport详解
- ClassLoader机制
- jenkins插件pipeline的简单使用
- sysfs
- String To Integer(atoi)
- STL中list实现降序排列
- ViewStub惰性装载控件
- 恩,今天是被cin.get()戏弄。
- listview当选中某一个item时设置背景色其他的不变
- VC常用小知识
- NSMutableDictionary对象用set方法初始化的键值真的不可修改吗
- android-设计模式的应用
- sql server行版本控制的隔离级别
- Unity3D中Layers和LayerMask解析