【问题标题】:template argument deduction/substitution failed: is there no first, second for map?模板参数扣除/替换失败:地图没有第一,第二吗?
【发布时间】:2019-04-18 20:46:43
【问题描述】:

我希望使用 stl std::sort()std::map 进行排序,但在 geeksforgeekside 上出现错误(无法粘贴整个错误,请参阅链接)

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int,int> m{
        {1,11},
        {2,5},
        {3,0}
    };
    sort(begin(m),end(m),[](auto a, auto b){return a.second < b.second;});
    for(auto i: m)
        cout<<i.first<<" "<<i.second<<endl;
    return 0;
}

我试过了

sort(m.begin(),m.end(),[](pair<int,int> a, pair<int,int> b){returna.second < b.second;});

但问题仍然存在,std::map 没有 firstsecond 吗??

【问题讨论】:

  • std::map 不能以这种方式工作。唯一可以实际排序的容器是std::vector
  • @SamVarshavchik std::dequestd::array 想和你谈谈
  • std::vector&lt;std::pair&lt;const int, int&gt;&gt; v{m.begin(), m.end()}; std::sort(v.begin(), ..);
  • 我不明白为什么人们不赞成它?如果我已经知道我为什么要问这个问题?用我所缺少的参考链接写下评论比仅仅投反对票要好。
  • @Jarod42 这行不通,因为具有 const 数据成员的对不能复制/移动分配

标签: c++ stl c++14 stdmap stl-algorithm


【解决方案1】:

您不能使用std::sort()std::map 进行排序。

如您所见,在this page 中,std::sort() 的要求

类型要求:RandomIt必须满足ValueSwappable和RandomAccessIterator的要求。

std::map 的迭代器不是 RandomAccessIterator(就像 std::vectorstd::deque 的迭代器一样)。

无论如何,std::map 是一种自分类容器。

没有意义的排序。有意义,如果需要,根据另一个比较器对其进行排序,您可以通过 std::map 的第三个模板参数来解释它(默认:std::less,根据 key`)。

【讨论】:

    【解决方案2】:

    这是一张地图,按设计在按键上排序。

    您不能按值对其进行排序。

    另外,不要使用bits/stdc++.h

    【讨论】:

    • 但是在这里看到第 41 行的最后一个代码cplusplus.com/forum/general/24427 他不也在做同样的事情吗??
    • 不,看代码sort(v.begin(),v.end(),Sort_by);,他是在向量上做的。
    猜你喜欢
    • 2013-06-20
    • 2019-09-11
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多