map及set中自定义比较函数

本文介绍了C++标准模板库(STL)中的map和set容器如何实现基于红黑树的平衡二叉检索树结构,并通过实例展示了如何自定义比较函数来控制元素的排序方式。适用于希望深入了解C++容器内部机制及自定义排序规则的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先对于map如果采用默认的比较函数,是按键值由小到大插入元素的。。

set和map集合容器实现了红黑树的平衡二叉检索树的数据结构,平衡二叉检索树使用中序遍历的算法。

#include<set>
#include<iostream>
#include<string>
#include<map>//map是按键值排序
#include<algorithm>
using namespace std;
struct info//结构体时直接在结构体中重载即可
{
	string name;
	float score;
	bool operator< (const info &a) const
	{return a.score<score;}
};
int main()
{
	cout<<"please input a integer:  "<<endl;
	int n;
	cin>>n;
	map<info,int>ms;
	for(int i=0;i!=n;++i)
	{
		info pos;
		cin>>pos.name>>pos.score;
		ms.insert(make_pair(pos,1));
	}
	map<info,int>::iterator it;
	for(it=ms.begin();it!=ms.end();++it)
	cout<<(it->first).name<<"  "<<(it->first).score<<endl;
	 return 0;
}
//非结构体时

struct cmp//假如键值是int类型
{
	bool operator()(const int &a,const int &b)
	{return a>b;}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值