简体   繁体   English

如果 KEY 是 std::list 或 std::vector 而不是值,则 std::map 的默认行为是什么?

[英]What is the default behavior of a std::map if, rather than the value, the KEY is a std::list or std::vector?

For example, these cases:例如,这些情况:

using stringlist = std::list<string>;
    
std::map<stringlist, int> orderedMap;
std::unordered_map<stringlist, int> unorderedMap;

How will comparing keys in orderedMap work?比较orderedMap中的键如何工作? Would it compare all items ('sub-keys') in the key one by one in lexical order?它会按词汇顺序逐一比较键中的所有项目(“子键”)吗?

How will computing hash in unorderedMap work?unorderedMap中计算 hash 将如何工作?

An ordered map , by default, uses std::less to compare keys, which by default just does lhs < rhs .默认情况下,有序的map使用std::less来比较键,默认情况下只执行lhs < rhs

The behavior of vector 's operator < is described here:https://en.cppreference.com/w/cpp/container/vector/operator_cmp vectoroperator <的行为在这里描述:https://en.cppreference.com/w/cpp/container/vector/operator_cmp

And that of list is here: https://en.cppreference.com/w/cpp/container/list/operator_cmp list在这里: https://en.cppreference.com/w/cpp/container/list/operator_cmp

Yes, they just do a lexicographical comparison, ie they compare their elements one by one.是的,他们只是做一个字典比较,即他们一个一个地比较他们的元素。

You can override the behavior by supplying a custom comparison as the third template parameter to map .您可以通过将自定义比较作为第三个模板参数提供给map来覆盖该行为。


The default behavior of unordered_map is to use std::hash . unordered_map的默认行为是使用std::hash std::hash does not have specializations for vector and list , so they are not usable as keys. std::hash没有针对vectorlist的特化,因此它们不能用作键。 The code should not compile.代码不应编译。 Try it here: https://godbolt.org/z/kgKmKS在这里试试: https://godbolt.org/z/kgKmKS

You need to override the behavior by supplying a custom hasher as the third template argument to unordered_map .您需要通过提供自定义哈希作为unordered_map的第三个模板参数来覆盖该行为。 You can use Boost.Hash, which supports the standard containers: https://www.boost.org/doc/libs/1_73_0/doc/html/hash/reference.html可以使用Boost.Hash,它支持标准容器: https://www.boost.org/doc/libs/1_73_0/doc/html/hash/reference.ZFC35FDC70D5FC69D2698EZ83A82

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM