gpt4 book ai didi

c++ - std::map 和 std::unordered_set 中的类类型

转载 作者:行者123 更新时间:2023-11-30 04:12:30 24 4
gpt4 key购买 nike

我想知道为什么 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 中 < key,value > 的值,并且它们都是声明中类型 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 函数散列?谢谢

最佳答案

"declaration of std::unordered_set s shadows a parameter"

这与集合无关。

您将其命名为与函数参数相同的名称。

重命名它。

不过,请确保您的值类型具有关联的散列函数和相等函数;回想一下,对于您的 map ,您的 类型需要一个排序函数。

关于c++ - std::map 和 std::unordered_set 中的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19824608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com