【问题标题】:Why can't I use lambda to sort std::map by value为什么我不能使用 lambda 按值对 std::map 进行排序
【发布时间】:2018-10-01 23:33:35
【问题描述】:
#include <iostream>
#include <map>
#include <utility>
#include <algorithm>


int main()
{
        std::map<int, std::string> m;
        m[2] = "abc";
        m[1] = "bcd";

        auto cmp = [](std::pair<int, std::string>  a, std::pair<int, std::string>  b)
        {
                return a.second != b.second ? a.second < b.second : a.first < b.first;
        };
        std::sort(m.begin(), m.end(), cmp);
        for (auto it = m.begin(); it != m.end(); ++it)
        {
                std::cout<<it->first<<std::endl;
                std::cout<<it->second<<std::endl;
        }

        return 0;
}

我想按它的值而不是它的键对地图进行排序,所以我按照上面的代码进行编码。

我刚刚阅读了这个链接,这就是我这样编码的原因:std::map, how to sort by value, then by key

但它产生了一个错误:

Severity    Code    Description Project File    Line    Suppression State
Error   C2784   'unknown-type std::operator -(const std::move_iterator<_RanIt> &,const std::move_iterator<_RanIt2> &)': could not deduce template argument for 'const std::move_iterator<_RanIt> &' from 'std::_Tree_unchecked_iterator<_Mytree>'   testcpp c:\program files (x86)\microsoft visual studio\2017\enterprise\vc\tools\msvc\14.10.25017\include\algorithm  2908

【问题讨论】:

  • 你应该重新阅读链接。
  • 请注意,链接的问题排序为vector,而不是map。地图已按键排序以支持快速查找,并且无法重新排序。 (具体的错误信息来自std::sort,需要一个随机访问迭代器,而地图没有)。
  • std::map 是一个排序容器;并按key排序(第一种类型的pair);您可以更改排序功能(使用 std::map 的第三个默认模板参数),但使用 std::sort 对其进行排序没有任何意义。

标签: c++ sorting c++11 dictionary


【解决方案1】:
auto cmp = [](std::pair<int, std::string>  a, std::pair<int, std::string>  b)
    {
            return a.second != b.second ? a.second < b.second : a.first < b.first;
    };

这就是问题所在。

谓词的参数应该是key_type可以隐式转换的类型

而您不应该将std::sort 应用于std::map。一个原因是这个操作是冗余(参见下面的参考资料),另一个是keys 有const 类型。

http://en.cppreference.com/w/cpp/container/map

还有一个建议:

将谓词的参数类型声明为 对 const 的引用

【讨论】:

  • 您本可以发表评论。
  • @AniketChowdhury 感谢您的建议。但是你能告诉我为什么这应该是评论吗?我想我已经回答了这个问题。
  • 那是在你编辑之前。在 cmets 中粗鲁比写一个答案更容易,它不会造成混乱。
  • 你也可以在 lambdas 中使用auto。
猜你喜欢
  • 1970-01-01
  • 2018-09-05
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 2019-05-03
  • 1970-01-01
相关资源
最近更新 更多