c++ - 为什么我不能使用 lambda 按值对 std::map 进行排序

标签 c++ sorting c++11 dictionary

#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;
}

我想按值而不是键对 map 进行排序,因此我按上面的代码进行编码。

我刚刚阅读了这个链接,这就是我编写这样的代码的原因: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

最佳答案

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。一个原因是此操作冗余(请参阅下面的引用资料),另一个原因是key 具有const 类型。

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

还有一个建议:

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

关于c++ - 为什么我不能使用 lambda 按值对 std::map 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49955374/

相关文章:

c++ - 从 C++ 中的 int ** 数组访问元素

mysql - 通过 IN 子句对 MySQL 查询结果进行排序

c++ - 如果我使用UMat并在opencv中关闭GPU处理,速度会有所不同吗?

c++ - C++ 映射及其内容的问题

javascript - 无法访问获取的数组元素

c++ - 使用 lambda 函数时可能发生堆栈溢出?

c++ - 如何在 C++ 中获取重载方法的返回类型?

c++ - std::reference_wrapper 对比整数&

c++ - 调用内联函数 C++

php - 使用 $_GET 和下拉列表传递变量