multimap排序

如果键值是string型,直接输出就可以了,multimap是排好序了的,如果你要用C风格字符串,就自定义一个排序规则,需要在创建 multimap的时候做:

#include <map>
#include <iostream>
#include <cstring>
using namespace std;

struct cstrcmp_less
{
    bool operator () (const char* a, const char* b)
    {
        return strcmp(a, b) == -1 ? 1 : 0;
    }
};

int main()
{
    multimap<const char*, const char*, cstrcmp_less> xx;
    xx.insert(make_pair("12","22"));
    xx.insert(make_pair("23","22"));
    xx.insert(make_pair("14","22"));
    xx.insert(make_pair("11","22"));
    
    for(multimap<const char*, const char*>::iterator it = xx.begin(); it != xx.end(); ++it)
        cout << it->first << endl;
}

C++ STL中标准关联容器set, multiset, map, multimap内部采用的就是一种非常高效的平衡检索二叉树:红黑树,也成为RB树(Red-Black Tree)。
  map和set的树建立之时就会自动排好序,之前使用map,觉得按value排序很麻烦,要建一个multimap将原map倒置存储。如何只用一个map实现value的排序呢?将key 和 value建一个结构体,再将结构体作为key建一个map。
  而排序当然要写比较函数,这个又如何解决呢?之前没去想map构造map<T1, T2>时,其实是有个默认的比较函数 map<T1, T2, less<T1>> ,即按key的升序排列,我们可以重写比较函数来实现我们想要的排序(value)。假设string是key, int是value;
  代码如下:
  #include<iostream>
  #include<map>
  #include<string>
  using namespace std;
  struct A
  {
  string s;
  int n;
  };
  class KeyComp
  {
  public:
  bool operator()(const A& a1, const A& a2) const
  {
  return (a1.n < a2.n ||(a1.n == a2.n && a1.s < a2.s));
  }
  };
  int main()
  {
  map<A, int, KeyComp> m;
  map<A, int, KeyComp>::iterator it;
  A rec;
  while(cin >> rec.s >> rec.n)
  {
  m[rec]++;
  }
  for(it = m.begin(); it != m.end(); it++)
  {
  cout << it->first.s << " " << it->first.n << " " << it->second;
  cout << endl;
  }
  return 0;
  }
  #include<iostream>
  #include<map>
  #include<string>
  using namespace std;
  struct A
  {
  string s;
  int n;
  };
  class KeyComp
  {
  public:
  bool operator()(const A& a1, const A& a2) const
  {
  return (a1.n < a2.n ||(a1.n == a2.n && a1.s < a2.s));
  }
  };
  int main()
  {
  map<A, int, KeyComp> m;
  map<A, int, KeyComp>::iterator it;
  A rec;
  while(cin >> rec.s >> rec.n)
  {
  m[rec]++;
  }
  for(it = m.begin(); it != m.end(); it++)
  {
  cout << it->first.s << " " << it->first.n << " " << it->second;
  cout << endl;
  }
  return 0;
  }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值