c++ list容器 排序算法详解 代码示例

关注小韩 轻松编程 一起由浅入深
解析都在代码注释里 废话不多说 上菜 !!!

#include
#include
#include
using namespace std;

class  Person {
public:
	Person(string name,int age,int height)  //构造函数
	{
		this->m_name = name;
		this->m_age = age;
		this->m_height = height;
	}

	string m_name;
	int m_age;
	int m_height;
};


void listprint(list<Person>const v)   //打印容器的值
{
	for (list<Person>::const_iterator it = v.begin(); it != v.end(); it++)
		cout << "姓名:" << (*it).m_name << "  年龄:" << (*it).m_age << "  身高:" << (*it).m_height << endl;
	cout << endl;
}

bool  compare(Person p1, Person p2)   //排序函数(sort的参数)   //note:   bool数据类型 及要操纵的数据类型
{
	if (p1.m_age == p2.m_age)       //年龄相同情况下  身高升序
		return p1.m_height < p2.m_height;
	else
		return p1.m_age < p2.m_age;  //年龄升序  同年龄则按身高升序
}


void test()
{
	list<Person> v;  //大容器  盛放每个人的信息

	Person p1("张三", 35, 175);   //六个人
	Person p2("李四", 45, 180);
	Person p3("王五", 40, 170);
	Person p4("赵六", 25, 190);
	Person p5("孙七", 35, 160);
	Person p6("刘八", 35, 200);

	v.push_back(p1);  //把每个人都放进容器
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);
	v.push_back(p5);
	v.push_back(p6);
	cout << "排序前" << endl;
	listprint(v);  //打印每个人的信息

	cout << "排序后" << endl;
	v.sort(compare);  //排序//年龄升序  同年龄则按身高升序   
	listprint(v);
}



int main()
{

	test();
	system("pause");
	return 0;
}

码字不易 有帮助记得点赞哦
有疑问欢迎评论区留言!!!

你可能感兴趣的:(stl,c++,数据结构,算法)