0
点赞
收藏
分享

微信扫一扫

map容器排序自定义类型数据----C++

微笑沉默 2022-03-11 阅读 50

要求:利用map容器排序自定义类型数据
注意:对于自定义数据类型,map必须要指定排序规则,与set容器一样,且map排序是按照key进行的。

上代码:

#include<iostream>
#include<string>
#include<map>

using namespace std;
class Person
{
public:
	Person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	string m_name;
	int m_age;
};

class myCompare
{
public:
	bool operator()(Person p1, Person p2)const
	{
		return p1.m_age > p2.m_age;
	}
};

void test01()
{
	map<Person, int,myCompare>m;
	Person p1("刘备", 24);
	Person p2("关羽", 28);
	Person p3("张飞", 26);
	Person p4("赵云", 22);
	m.insert(make_pair(p1,100));
	m.insert(make_pair(p2, 800));
	m.insert(make_pair(p3, 200));
	m.insert(make_pair(p4, 300));

	for (map<Person, int, myCompare>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << "姓名:" << it->first.m_name << "\t年龄:" << (*it).first.m_age << "\t收入:" << it->second << endl;
	}
}

int main()
{
	test01();
	system("pause");
	return 0;

}
举报

相关推荐

0 条评论