按规则对对象数组进行排序
今天,小菜帮网友调试了个小程序,不想浪费就贴出来了。代码的用途:存在一个类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;
}

浙公网安备 33010602011771号