码迷,mamicode.com
首页 > 编程语言 > 详细

c++之map排序

时间:2019-02-25 21:46:46      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:key   begin   after   有序容器   strong   com   cond   pair   str   

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值进行了排序。

c++之map排序

标签:key   begin   after   有序容器   strong   com   cond   pair   str   

原文地址:https://www.cnblogs.com/ChrisCoder/p/10433543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!