c++之map排序

c++之map排序

为了实现查找,map在插值时已经对key值进行了排序(使用红黑树结构)。如果想对map的value值进行排序,由于sort函数只可以对有序容器进行排序,那么可以将map转为vector后进行排序。

#include <iostream>
#include <map>
#include <algorithm>

// 对map不能直接排序, 使用vector进行排序

bool compVec(const std::pair<int, float>& a, const std::pair<int, float>& b)
{
  return a.second > b.second;
}

struct compByValue
{
  bool operator()(std::pair<int, float>& lhs, std::pair<int, float>& rhs)
  {
    return lhs.second > rhs.second;
  }
};

int main(int argc, char** argv)
{
  std::map<int, float> map;
  map[2] = 3.9;
  map.insert(std::pair<int, float>(7, 28.5));
  map.insert(std::pair<int, float>(4, -0.99));
  map.insert(std::map<int, float>::value_type(1, -0.17));
  map.insert(std::make_pair(6, 15.7));
  
  std::cout << "before sort" << std::endl;
  for (auto it = map.begin(); it != map.end(); ++it)
  {
    std::cout << it->first << " : " << it->second << std::endl;
  }
  
  // turn into vector
  std::vector<std::pair<int, float> > map_vec(map.begin(), map.end());

  std::sort(map_vec.begin(), map_vec.end(), compVec);
  // std::sort(map_vec.begin(), map_vec.end(), compByValue());

  std::cout << "after sort(descending order): " << std::endl;
  for (auto it = map_vec.begin(); it != map_vec.end(); ++it)
  {
    std::cout << it->first << " : " << it->second << std::endl;
  }

  return 0;
}

输出结果为:

before sort
1 : -0.17
2 : 3.9
4 : -0.99
6 : 15.7
7 : 28.5
after sort(descending order):
7 : 28.5
6 : 15.7
2 : 3.9
1 : -0.17
4 : -0.99

注: 由结果可知,在map插入后,已经按照key值进行了排序。

转载于:https://www.cnblogs.com/ChrisCoder/p/10433543.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值