c++ - 如何将比较器传递给内部 map ?

标签 c++ dictionary

我需要实现两个嵌套映射,并为内部映射定制一个比较器。

我有:

struct Rank {
    Rank() = default;
    int rank = 0;
    bool condition = false;
};

和比较器

struct compareRank {
    bool operator()(const Rank& lhs, const Rank& rhs) const {
        return lhs.rank < rhs.rank;
    }
};

在我的 main() 函数中,我声明:

map<int, map<string, Rank, compareRank>> db;

这背后的想法如下:内部 map 应按其等级对其字符串进行排序。

但是,当我尝试这样做时:

db[3]["hello"] = Rank();

编译说:

no matching function for call to object of type 'const compareRank'

我不知道怎么解决。

最佳答案

std::map是一个基于 key 的容器。这意味着它对键进行排序,而不是对值进行排序。 compareRank需要 Rank本地图试图对 std::string 进行排序时键。

如果您不需要 std::string key 那么你可以考虑 std::set<Rank> .

如果您需要同时拥有 std::stringRank作为 key ,您可以使用 boost::bimap

关于c++ - 如何将比较器传递给内部 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49631868/

相关文章:

scala - 如何访问/初始化和更新可变映射中的值?

python - 将字典键连接到字符串

java - 在不同 map 上使用按键

c++ - 在 C++ 中使用 Gdiplus 创建透明位图

c++ - 从 Visual Basic 调用 C++ DLL

c++ - GCC/LD找不到链接库

c++ - 旧 vector 是否被清除?如果是,如何以及何时?

javascript - 在 Typescript 中,使用公共(public)字符串字段作为键从 Array<T> 构造 Map<string,T> 时出错

javascript - D3 从纬度和经度寻找路径

c++ - 基本类型的 std::vector 的默认值