#include<map>
#include<iomanip>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int,double>CustomPair;
void print(map<int,double>& m)
{
map<int,double>::iterator it=m.begin();
for(;it!=m.end();it++)
{
CustomPair p1=(pair<int,double>) (*it);
cout<<p1.first<<",";
cout<<fixed<<setprecision(2)<<p1.second<<";"<<endl;
}
}
void printg(map<int,double,greater<int> >&m)
{
map<int,double,greater<int> >::iterator it=m.begin();
for(;it!=m.end();it++)
{
CustomPair p1=(pair<int,double>) (*it);
cout<<p1.first<<",";
cout<<fixed<<setprecision(2)<<p1.second<<";"<<endl;
}
}
void printl(map<int,double,less<int> >&m)
{
map<int,double,less<int> >::iterator it=m.begin();
for(;it!=m.end();it++)
{
CustomPair p1=(pair<int,double>) (*it);
cout<<p1.first<<",";
cout<<fixed<<setprecision(2)<<p1.second<<";"<<endl;
}
}
bool cmp(const CustomPair &a,const CustomPair &b)
{
return a.second>b.second;
}
void printv(CustomPair &a)
{
cout<<a.first<<" "<<a.second<<endl;
}
int main()
{
map<int,double>::iterator itm;
map<int,double,greater<int> >::iterator itmg;
map<int,double,less<int> >::iterator itml;
map<int,double>m1; //以键值升序排序
map<int,double,greater<int> >m2; //以键值降序排序
m1.insert(CustomPair(1,2.0));
m1.insert(CustomPair(4,8.0));
m1.insert(CustomPair(5,11.0));
m1.insert(CustomPair(6,6.0));
m1.insert(CustomPair(2,5.0));
m1.insert(CustomPair(3,7.0));
cout<<"m1:"<<endl;
print(m1);
m2.insert(CustomPair(1,2.0));
m2.insert(CustomPair(4,8.0));
m2.insert(CustomPair(5,11.0));
m2.insert(CustomPair(6,6.0));
m2.insert(CustomPair(2,5.0));
m2.insert(CustomPair(3,7.0));
cout<<"m2(greater<int>()):"<<endl;
printg(m2);
//ma=m2.get_allocator();
map<int,double>m5(less<int>(),ma); //以降序排列,申请空间排序方式不同 ,但迭代器一样 map<int,double,less<int> >::iterator it=m.begin();
m5.insert(CustomPair(16,1.0));
m5.insert(CustomPair(15,7.0));
m5.insert(CustomPair(24,9.0));
m5.insert(CustomPair(23,13.0));
m5.insert(CustomPair(32,21.0));
m5.insert(CustomPair(11,27.0));
cout<<"m5(less<int>:):"<<endl;
printl(m5);
vector<CustomPair>k_and_v(m5.begin(),m5.end());//用(map)CustomPair类型的m5初始化vector
sort(k_and_v.begin(),k_and_v.end(),cmp);
for_each(k_and_v.begin(),k_and_v.end(),printv);
return 0;
}