3.9.6 map容器排序

//map容器排序
#include<iostream>
using namespace std;
#include<map>

class MyCompare
{
public:
	bool operator()(int v1, int v2)
	{
		//降序
		return v1 > v2;
	}
};
void test01()
{
	map<int,int,MyCompare>m;
	m.insert(make_pair(1, 10));
	m.insert(make_pair(2, 10));
	m.insert(make_pair(3, 10));
	m.insert(make_pair(4, 10));
	m.insert(make_pair(5, 10));
	for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << "key = " << it->first << " value = " << it->second << endl;
	}

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

#include<iostream> #include<algorithm> #include<string> #include<map> using namespace std; //3.9.6 map容器排序 //学习目标:map容器默认排序规则为 按照key值进行 从小到大排序,掌握如何改变排序规则 //主要目标点:利用仿函数,可以改变排序规则 class myCompare{ //仿函数的本质是类 其对象称为函数对象 public: bool operator() (int v1,int v2) { //降序 return v1 > v2; } }; //map内置数据类型排序 void test01() { map<int,int,myCompare> m; //在插入数据前更改排序规则 还是按照key值排序 默认以key值参考做升序排列 m.insert(make_pair(1,50)); m.insert(make_pair(3,40)); m.insert(make_pair(5,20)); m.insert(make_pair(4,10)); m.insert(make_pair(2,30)); //遍历 for(map<int,int,myCompare>::iterator it = m.begin();it!=m.end();it++) { cout<<"key = "<<it->first<<" value = "<<it->second<<endl; } } //map自定义数据类型排序 class person{ public: person(string name , int age) { m_Name = name; m_Age = age; } string m_Name; int m_Age; }; //operator() 创建仿函数 class comparePerson{ public: bool operator() (person &p1,person &p2) { return p1.m_Age > p2.m_Age; } }; //自定义数据类型排序 void test02() { //容器创建 map<int,person,comparePerson> m; person p1("Nami",24); person p2("Anne",20); person p3("AgeHa",17); m.insert(pair<int,person> (1,p2)); //第一种插入方式 m.insert(make_pair(2,p3)); //第二种插入方式 m.insert(map<int,person,comparePerson>::value_type(3,p1)); //第三种插入方式 for(map<int,person,comparePerson>::iterator it = m.begin();it!=m.end();it++) { cout<<"key = "<<it->first<<" name = "<<(it->second).m_Name<<" age = "<<(it->second).m_Age<<endl; } cout<<endl; } int main() { //test01(); test02(); return 0; } 请告知我的代码为什么会报错 错误如下[Error] no match for call to &#39;(comparePerson) (std::pair<const int, person>::first_type&, const int&)&#39;
最新发布
09-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值