按规则对对象数组进行排序
来源:互联网 发布:数据资产管理领悟 编辑:程序博客网 时间:2024/06/11 22:05
今天,小菜帮网友调试了个小程序,不想浪费就贴出来了。代码的用途:存在一个类Person,产生一系列的对象,要求按年龄从小到大对对象数组进行排序,一般情况下,对象较小时可以vector<Person>处理,但对象较大时,很浪费内存,用vector<Person*>处理较为合理,但两个版本有细微的差别,代码如下,希望对各位有用。
// 处理指针数组的情况
#include <iostream>
#include <vector>#include <string>
#include <algorithm>
#include <functional>
using namespace std;
class Person {
public:
int age;
string name;
public:
//...
Person(){};
~Person(){};
Person(int n,string str){
age = n;
name = str;
}
void print () const {
std::cout <<"name: "<<name<<"\t";
std::cout <<"age: "<< age<< std::endl;
}
};
// 按年龄从小到大排序
bool lessage(Person* p1,Person* p2)
{
return (*p1).age < (*p2).age;
}
int main()
{
std::vector<Person*> coll(5);
Person p1(20,"p1");
Person p2(31,"p2");
Person p3(12,"p3");
Person p4(13,"p4");
Person p5(4,"p5");
coll[0] = &p1;
coll[1] = &p2;
coll[2] = &p3;
coll[3] = &p4;
coll[4] = &p5;
std::vector<Person*>::iterator Iter;
std::cout<<"排列前的: "<<std::endl;
for( Iter = coll.begin(); Iter != coll.end(); Iter++) // 这里不能使用for_each (*coll.begin(), *coll.end(),
// mem_fun_ref(&Person::print));否则会出现乱码
{
(*Iter)->print();
}
sort(coll.begin(),coll.end(),lessage);
for( Iter = coll.begin(); Iter != coll.end(); Iter++)
{
(*Iter)->print();
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 一般的数组
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
class Person {
public:
int age;
string name;
public:
//...
Person(){};
~Person(){};
Person(int n,string str){
age = n;
name = str;
}
void print () const {
std::cout <<"name: "<<name<<"\t";
std::cout <<"age: "<< age<< std::endl;
}
};
bool lessage(const Person& p1,const Person& p2)
{
return p1.age < p2.age;
}
int main()
{
std::vector<Person> coll(5);
Person p1(20,"p1");
Person p2(31,"p2");
Person p3(12,"p3");
Person p4(13,"p4");
Person p5(4,"p5");
coll[0] = p1;
coll[1] = p2;
coll[2] = p3;
coll[3] = p4;
coll[4] = p5;
std::cout<<"排列前的: "<<std::endl;
for_each (coll.begin(), coll.end(),
mem_fun_ref(&Person::print));
sort(coll.begin(),coll.end(),lessage);
std::cout<<"排列后的: "<<std::endl;
for_each (coll.begin(), coll.end(),
mem_fun_ref(&Person::print));
return 0;
}
- 按规则对对象数组进行排序
- 对对象按对象的某个属性进行排序
- 排序(对对象进行排序)二
- Collections.sort()对对象进行排序
- 对对象的某些属性进行排序
- Collections.sort()对对象进行排序
- Comparable接口对对象进行排序
- C#中通过实现IComparable接口对对象数组进行排序
- 【LeetCode】two num 利用comparable接口 对对象进行排序
- Comparable接口实现对对象数组的排序
- STL对对象的排序
- Java列表对对象排序
- 利用compare对对象排序
- Java对对象进行保存和读取
- angularjs中的$watch,对对象进行监视
- 利用发反射对对象进行赋值
- ThinkPHP中的过滤函数[可以对对象,数组,字符串进行递归过滤]
- 默认和静态接口方法(lumbda对对象进行排序)
- 存储过程(三)
- 读取TEXT
- 20110915
- Eclipse 常用快捷键
- qt 实现的 lua 编辑器
- 按规则对对象数组进行排序
- 裸骑不裸头
- 获得系统所有字体
- 数据挖掘中的简单预测
- Hash算法系列-应用(加密)
- 工具栏上添加平面下拉控件
- 自动化测试框架设计时应该考虑的20个方面
- 读书笔记(第六讲)-流程控制语句
- 将mysql数据库数据转移到sql server 2008