一、排序案例
案例描述 将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高。 排序规则 按照年龄进行排序,如果年龄相同按照身高及进行降序。
二、代码示例
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
#include <list>
using namespace std
;
class Person
{
public
:
Person(string name
,int age
,int height
)
{
m_name
= name
;
m_age
= age
;
m_height
= height
;
}
string m_name
;
int m_age
;
int m_height
;
};
void print(const list
<Person
>& l
)
{
for(list
<Person
>::const_iterator it
= l
.begin(); it
!= l
.end(); it
++)
{
cout
<< it
->m_name
<<" "<<it
->m_age
<<" "<<it
->m_height
<< endl
;
}
cout
<< endl
;
}
bool
myCompare(Person
&p1
, Person
&p2
)
{
if(p1
.m_age
== p2
.m_age
)
{
return p1
.m_height
> p2
.m_height
;
}
else
{
return p1
.m_age
> p2
.m_age
;
}
}
void test2()
{
list
<Person
>l
;
Person
p1("lcl",23,169);
Person
p2("xqq",20,164);
Person
p3("hqq",22,170);
Person
p4("wxr",22,165);
Person
p5("lxw",23,169);
l
.push_back(p1
);
l
.push_back(p2
);
l
.push_back(p3
);
l
.push_back(p4
);
l
.push_back(p5
);
print(l
);
l
.sort(myCompare
);
print(l
);
}
int main()
{
test2();
return 0;
}
三、结果输出
转载请注明原文地址: https://lol.8miu.com/read-27654.html