如何使地图按值排序C ++ [英] How to make a map sort by value C++

查看:43
本文介绍了如何使地图按值排序C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用自定义比较器按值对地图进行排序,但我不明白为什么我一直收到没有匹配调用compareByVal的错误"的错误提示

I was trying to make a map sort by value using a custom comparator but I couldn't figure out why I kept getting the error of "no matching call to compareByVal"

这是我在main.cpp中拥有的内容:

Here's what I had in my main.cpp:

#include <map>
#include <iostream>

struct compareByVal {
  bool operator[](const std::pair<int,int> & a, const std::pair<int,int> & b)
    return a.second < b.second;
}

int main() {
  std::map<int,int,compareByVal> hash;
  hash[1] = 5;
  hash[2] = 2;
  hash[3] = 10;

  std::cout << hash.begin()->first << std::endl;
}

推荐答案

简单地说,您不能.不确定使用的是哪个编译器,但是clang和gcc都给出有用的消息.带有上下文.

Simply put, you cannot. Not sure which compiler you're using, but clang and gcc both give useful messages. with context.

c语: static_assert(__ is_invocable< _Compare& ;、 const _Key& ;、 const _Key&> {},

gcc: if(__i == end()|| key_comp()(__ k,(* __ i).first))

您会看到clang和gcc都只用 key 而不是值来调用compare方法.这就是地图的工作原理.

You can see that clang and gcc are both calling the compare method with only they key, and not a value. This is simply how maps work.

如果要按值排序,则必须创建自己的自定义映射,或者更实际地,将值用作键.创建自己的地图来实现此目标比您想象的要困难得多,因为修改任何值后都必须对其进行排序.

If you want to sort by value, you would have to create your own custom map, or, more realistically, use the value as the key instead. Creating your own map to achieve this would be more difficult than you'd think, since it would have to sort after any value is modified.

这篇关于如何使地图按值排序C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆