我一直在看Unordered_set的构造函数。是否不可能在不设置哈希桶数的情况下使用自定义分配器实例构造Unrodered_set?我真的宁愿不要弄乱实现详细信息,因为我想要自定义分配器,并且该类型不提供默认值的定义。 MSDN仅给构造函数提供三个超载,它们都不是非常有用的。

编辑:神圣的废话。我对STD :: HASH的STL实现不会专注于具有自定义分配器类型的字符串 - 它只能进行明确的Typedefs std :: String :: string and std :: Wstring。我的意思是,我能理解不想尝试哈希随机字符串,而只是因为它有自定义分配器吗?这让我感到厌恶。

tokens(std::unordered_set<string>().bucket_count(), std::hash<string>(), std::equal_to<string>(), stl_wrapper::hash_set<string>::allocator_type(this))
template<typename Char, typename CharTraits, typename Allocator> class std::hash<std::basic_string<Char, CharTraits, Allocator>>
    : public std::unary_function<std::basic_string<Char, CharTraits, Allocator>, std::size_t> {
public:
    size_t operator()(const std::basic_string<Char, CharTraits, Allocator>& ref) const {
        return std::hash<std::basic_string<Char, CharTraits>>()(std::basic_string<Char, CharTraits>(ref.begin(), ref.end()));
    }
};

解决问题,但是冗余的结构和复制? ewwwww。

有帮助吗?

解决方案

那很奇怪,但是你是对的。我认为认为使用默认值支持所有可能的参数组合是过分的。

我能想到的最好的方法是构造一个空的 unordered_set 使用所有默认设置,请从中获取默认存储桶计数 unordered_set::bucket_count, ,然后在实例化实际想要的容器时将其用作输入。

unordered_set<int> temp;
size_t buckets = temp.bucket_count;
unordered_set<string> actual(buckets, Hash(), Pred(), 
    YourAllocator(param1 /*, etc */));

其他提示

因为您正在写 Allocator, ,也有意义地控制水桶的数量,毕竟两者都是与内存有关的:)

史蒂夫(Steve)如果您不想愿意,请给予该方法的核心,现在让我提出一个助手功能:)

template <typename T>
size_t number_buckets()
{
  std::unordered_set<T> useless;
  return useless.bucket_count();
}

因此,有点(简单)的助手:

template <typename T, typename Hash, typename Pred, typename Allocator>
std::unordered_set<T,Hash,Pred,Allocator>
  make_unordered_set(Hash const& hash, Pred const& pred, Allocator const& alloc)
{
  static size_t const nbBuckets = number_buckets<T>();
  return std::unordered_set<T,Hash,Pred,Allocator>(nbBuckets, hash, pred, alloc);
}

效果很好 auto:

auto set = make_unordered_set<std::string>(Hash(), Pred(), Allocator(1,2,3));

当然,您也可以只需从自己喜欢的实现中撕掉不断的情况即可。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top