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

被折叠的 条评论
为什么被折叠?



