21xrx.com
2025-04-02 13:21:27 Wednesday
文章检索 我的文章 写文章
C++ Map 按 Value 排序
2023-06-28 13:42:57 深夜i     16     0
C++ Map Value 排序 Key

在 C++ 中,Map 是一个非常实用的容器,可以用来存储键-值对。这个容器使用红黑树实现,可以快速地插入和查找元素。但是,它默认按照键进行排序,如果我们想按照值排序,该怎么做呢?

有两种方法可以实现按照值排序的功能:

第一种方法是将 Map 中的键值对存储到 Vector 中,并使用 sort() 函数对 Vector 进行排序,然后再将排序后的键值对插入到新的 Map 中。这种方法的缺点是,需要额外的内存开销,并且在插入新的 Map 中时还需要进行查找操作,导致效率降低。

下面是这种方法的示例代码:

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
bool sortByValue(const pair<string, int>& a,
         const pair<string, int>& b)
  return a.second < b.second;
int main()
{
  map<string, int> m = { 90, "lisi",
             "wangwu", "zhaoliu"};
  vector<pair<string, int>> v(m.begin(), m.end());
  sort(v.begin(), v.end(), sortByValue);
  map<string, int> sortedMap;
  for (auto& p : v) {
    sortedMap.insert(p);
  }
  for (auto& p : sortedMap)
    cout << p.first << " " << p.second << endl;
  
  return 0;
}

第二种方法更加高效,它通过重载 Map 中的 operator<() 函数实现按照值排序。具体来说,我们需要将 Map 中的键值对进行反转,使值成为键,键成为值,然后在重载 operator<() 函数时按照反转后的键进行比较,实现按照值排序。

下面是这种方法的示例代码:

#include <iostream>
#include <map>
using namespace std;
class MapByValue {
public:
  bool operator() (const pair<string, int>& a,
           const pair<string, int>& b) const
  
    return a.second < b.second;
  
};
int main()
{
  map<string, int> m = {"zhangsan", "lisi",
             "wangwu", "zhaoliu"};
  map<int, string> tmpMap;
  for (auto& p : m) {
    tmpMap[p.second] = p.first;
  }
  map<int, string, MapByValue> sortedMap(tmpMap.begin(), tmpMap.end());
  for (auto& p : sortedMap)
    cout << p.second << " " << p.first << endl;
  
  return 0;
}

以上就是两种按照值排序的方法,选择哪一种方法取决于实际需求和场景。当然,还有其他的实现方式,读者可以自行探索。

  
  

评论区

请求出错了