【问题标题】:Sorting an STL Map from lowest to greatest value [duplicate]从最小值到最大值对 STL 映射进行排序[重复]
【发布时间】:2016-10-31 14:53:16
【问题描述】:

我有一个包含 String 键和 int 值的 STL 映射。我需要将项目放入具有 int 键和 String 值的新映射中,以便键从最低到最高排序。

例如,我有一个包含这些值(键、值)的地图:

"A", 5
"B", 2
"C", 8
"D", 4

我希望它们按照如下方式排列(键,值):

2, "B"
4, "D"
5, "A"
8, "C"

原始映射中的值成为键,键成为值。

我知道我需要将原始地图中的值添加到新地图中,但我不确定如何以从最低到最高排序的方式添加它们。

【问题讨论】:

    标签: c++ sorting dictionary


    【解决方案1】:

    std:map默认为按键排序

    Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).
    

    请阅读链接:http://www.cplusplus.com/reference/map/map/

    #include <iostream>
    #include <string>
    #include <iterator>
    #include <algorithm>
    #include <map>
    using namespace std;
    
    int main() {
        map<string, int> myMap;
        myMap["D"] = 4;
        myMap["C"] = 8;
        myMap["B"] = 2;
        myMap["A"] = 5;
        cout<<"before:"<<endl;
        for_each(myMap.begin(), myMap.end(), [](auto& element){cout<<element.first<<" "<<element.second<<endl;});
    
        map<int, string> otherMap;
        cout<<"after:"<<endl;
        for_each(myMap.begin(), myMap.end(), [&otherMap](auto& element){otherMap[element.second] = element.first;});
        for_each(otherMap.begin(), otherMap.end(), [](auto& element){cout<<element.first<<" "<<element.second<<endl;});
        return 0;
    }
    

    下面是代码示例: 输出是:

    before:
    A 5
    B 2
    C 8
    D 4
    after:
    2 B
    4 D
    5 A
    8 C
    

    所以你不要自己排序。

    【讨论】:

      【解决方案2】:

      对于原始映射中的每一对,反转该对并插入到另一个映射中。排序是自动的,因为std::map 是按键排序的。

      另外,如果您在原始映射中可能有多个具有相同数据的键(例如 "A""E" 都有数据 5),那么您需要改用 std::multimap

      【讨论】:

      • 那么当key是int时std::map会自动从小到大排序?
      • @Darren 是的,因为默认的排序行为是std::less&lt;&gt;
      • 好的,谢谢,这样就可以了。
      【解决方案3】:

      也许是这样的:

      std::map<std::string, int> old_map = ...;  // initialized somehow
      std::map<int, std::string> new_map;
      
      std::transform(old_map.begin(), old_map.end(),
        std::inserter(new_map, new_map.end()),
        [](decltype(old_map)::iterator it) {
          return std::make_pair(it->second, it->first);
        }
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-15
        • 2019-05-11
        • 2011-02-11
        • 2016-07-13
        • 1970-01-01
        • 2018-06-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多