簡體   English   中英

為什么我不能使用 lambda 按值對 std::map 進行排序

[英]Why can't I use lambda to sort std::map by value

#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
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 s 有const類型。

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

還有一個建議:

將謂詞的參數類型聲明為對 const引用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM