ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

如何制作st 11 :: weak_ptr的c 11 std :: unordered_set

2019-10-08 00:06:38  阅读:419  来源: 互联网

标签:unordered-set weak-ptr c c11 std


我有这样的集合:set< weak_ptr< Node>,owner_less< weak_ptr< Node> &GT &GT的setName;

它工作正常.但我想将它改为无序集.但是,当我这样做时,我会得到大约六页的错误.任何想法如何做到这一点?

查看了所有错误消息页面后,我发现了可能有用的行.

/usr/include/c++/4.7/bits/functional_hash.h:60:7: error: static assertion failed: std::hash is not specialized for this type
/usr/include/c++/4.7/bits/stl_function.h: In instantiation of ‘bool std::equal_to<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = std::weak_ptr<Node>]’:

解决方法:

由于unordered_sets是基于散列的,因此您必须为std :: weak_ptr数据类型提供哈希值function object.

如果你看一下unordered_set模板参数

template<class Key,
    class Hash = std::hash<Key>,
    class Pred = std::equal_to<Key>,
    class Alloc = std::allocator<Key> >
    class unordered_set;

你会注意到std :: unordered_set为你提供了一个默认的std :: hash<>模板参数.但由于std :: hash仅提供specific set数据类型的特化,因此您可能必须提供自己的数据类型.

您引用的错误消息告诉您,没有std :: hash<> std :: weak_ptr<>的专业化存在,所以你必须为此提供自己的散列函数:

template<typename T>
struct MyWeakPtrHash : public std::unary_function<std::weak_ptr<T>, size_t> {
   size_t operator()(const std::weak_ptr<T>& wp)
   {
      // Example hash. Beware: As zneak remarked in the comments* to this post,
      // it is very possible that this may lead to undefined behaviour
      // since the hash of a key is assumed to be constant, but will change
      // when the weak_ptr expires
      auto sp = wp.lock();
      return std::hash<decltype(sp)>()(sp);
   }
};

编辑:
您还需要提供相等函数,因为没有提供weak_ptr的std :: equal_to.
“Equality-compare std::weak_ptr” on Stackoverflow开始可能的方法:

template<typename T>
struct MyWeakPtrEqual : public std::unary_function<std::weak_ptr<T>, bool> {

   bool operator()(const std::weak_ptr<T>& left, const std::weak_ptr<T>& right)
   {
      return !left.owner_before(right) && !right.owner_before(left);
   }
};

所有这些结合起来给我们以下内容:

std::unordered_set<std::weak_ptr<T>,
                   MyWeakPtrHash<T>,
                   MyWeakPtrEqual<T>> wpSet;

标签:unordered-set,weak-ptr,c,c11,std
来源: https://codeday.me/bug/20191007/1869619.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有