21xrx.com
2025-03-27 17:04:28 Thursday
文章检索 我的文章 写文章
C++ Map 排序
2023-07-09 02:25:38 深夜i     --     --
C++ Map 排序

在 C++ 中,Map 是一个非常有用的数据结构,可以用来存储一组键-值对。Map 中的元素按照键值进行排序。但是,有时候我们需要按照其他方式进行排序,比如按照值或者按照自定义的规则进行排序。这时候就需要对 Map 进行排序操作。

C++ 中的 Map 排序可以通过定义自定义比较器来实现。这里以按照值进行排序为例进行说明。下面是一个 Map 定义的例子:

#include <iostream>
#include <map>
using namespace std;
int main() {
  map<int, int> myMap;
  myMap.insert(pair<int, int>(1, 10));
  myMap.insert(pair<int, int>(2, 20));
  myMap.insert(pair<int, int>(3, 30));
  myMap.insert(pair<int, int>(4, 40));
  myMap.insert(pair<int, int>(5, 50));
  return 0;
}

上述代码定义了一个 Map,其中键值对分别是 1, 2, 3, 4, 50。

现在,我们需要按照值的大小来对 Map 进行排序。定义一个自定义比较器:

struct cmp {
  bool operator () (const pair<int, int>& a, const pair<int, int>& b) const
    return a.second < b.second;
  
};

这里我们实现了一个函数对象 cmp,它重载了 operator() 操作符,可以用来比较两个键值对的值。

现在,我们可以使用该比较器对定义好的 Map 进行排序:


#include <iostream>

#include <map>

using namespace std;

struct cmp {

  bool operator () (const pair<int, int>& a, const pair<int, int>& b) const

    return a.second < b.second;

  

};

int main() {

  map<int, int, cmp> myMap;

  myMap.insert(pair<int, int>(1, 10));

  myMap.insert(pair<int, int>(2, 20));

  myMap.insert(pair<int, int>(3, 30));

  myMap.insert(pair<int, int>(4, 40));

  myMap.insert(pair<int, int>(5, 50));

  for (auto& it : myMap)

    cout << it.first << " " << it.second << endl;

  

  return 0;

}

代码中,定义了一个 Map myMap,并使用了 cmp 作为其比较器。运行代码后,输出结果为:


1 10

2 20

3 30

4 40

5 50

可以看到,输出的结果已经按照值进行了排序。

总的来说,C++ 中的 Map 排序非常灵活,可以按照各种方式进行排序。只需要定义不同的比较器即可。

  
  

评论区