STL list中对象排序
来源:互联网 发布:政府资助 知乎 编辑:程序博客网 时间:2024/05/01 22:57
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
- STL list中对象排序
- STL list中对象排序
- list中对象排序
- C++中STL List排序实现
- STL中list结构体元素排序
- STL LIST中自定义排序函数例子
- STL中list的排序算法
- 对List中对象排序
- 排序对象中List对象的用法
- STL list查找、删除、结构体实例化对象排序
- STL list 排序
- STL list 排序
- stl的list排序
- STL之list排序
- JAVA中对List中的对象排序
- 对List中对象属性进行排序
- java中List对象排序通用方法
- java中List对象排序通用方法
- ASP.NET 页生命周期概述
- Raid介绍
- zju 3635....
- Python线程指南
- Rally
- STL list中对象排序
- windows安装、开启和删除服务的bat笔记
- vc6.0资源
- c++ STL Map 用法 小于号重载和仿函数定义
- php 函数嵌套
- arcmap_polygon转坐标文件
- PowerDesigner生成sql语句和从SQL语句生成表的反向工程
- keil中函数变量定位方法
- Subsonic queries查询帮助