类类型为 std::map 和 std::unordered_set

class type in std::map and std::unordered_set

本文关键字:std unordered set map 类型      更新时间:2023-10-16

我想知道为什么std::map允许节点是用户定义的类型,而std::unordered_set却不允许?据我了解,我假设 std::map 是使用二叉树实现的,而 std::unordered_set 是一个哈希表。

例如

struct foo{
 int a;
 int b;
};
std::map<int,foo> m; //it is allowed, foo is the tree node that is value from the <int,foo> <key,value> pair

但是,这同样不能在 std::上编译unordered_set

std::underedset_set<foo> s //failed, "declaration of std::unordered_set<foo> s shadows a parameter"

这对我来说很奇怪,因为我认为 foo 是 hastable 中 <键、值>的值,它们都是声明中 K 类类型的模板参数。谢谢

template < class Key,                                     // map::key_type
       class T,                                       // map::mapped_type
       class Compare = less<Key>,                     // map::key_compare
       class Alloc = allocator<pair<const Key,T> >    // map::allocator_type
       > class map;
template < class Key,                        // unordered_set::key_type/value_type
       class Hash = hash<Key>,           // unordered_set::hasher
       class Pred = equal_to<Key>,       // unordered_set::key_equal
       class Alloc = allocator<Key>      // unordered_set::allocator_type
       > class unordered_set;

编辑1:

std::unordered_set<foo> s // failed again for different reason, which was really what I was asking
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/basic_string.h:3032:0,
                 from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/string:54,
                 from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/random:41,
                 from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/stl_algo.h:67,
                 from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/algorithm:63,
                 from ArrayTargetSum.cpp:10:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/functional_hash.h: In instantiation of ‘struct std::hash<foo>’:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/unordered_set.h:279:11:   required from ‘class std::unordered_set<foo>’
ArrayTargetSum.cpp:70:25:   required from here
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/functional_hash.h:60:7: error: static assertion failed: std::hash is not specialized for this type

我想从打印输出来看,原因是用户定义的类型无法通过 stl::hash 函数进行哈希处理?谢谢

"声明 std::unordered_set s 遮蔽参数"

这与布景无关。

您为其指定与函数参数相同的名称。

重命名它。

但是,请确保您的值类型具有关联的哈希和相等函数;回想一下,对于您的映射,您的类型需要一个排序函数。