代码之家  ›  专栏  ›  技术社区  ›  Alan

如何使用boost::thread::id作为无序的\u映射的键?

  •  3
  • Alan  · 技术社区  · 15 年前

    根据 documentation ,一个 boost::thread::id 对于每个正在运行的线程都可以认为是唯一的,并且可以在容器中使用,例如 std::set std::map (因为 < 运算符被重写 thread::id ).

    我的问题是我想用 线程::id 作为一把钥匙 boost::unordered_map 但是,它要求密钥是“可哈希的”(即支持哈希到 size_t

    所以我的问题是- 是否可以使用thread::id作为无序映射的键?

    4 回复  |  直到 15 年前
        1
  •  5
  •   Matthieu M.    15 年前

    您可以使用流媒体功能:

    struct Hasher
    {
      size_t operator()(const boost::thread::id& id)
      {
        std::ostringstream os; os << id; return hash(os.str());
      }
    };
    

    class thread::id
    {
    public:
        id();
    
        bool operator==(const id& y) const;
        bool operator!=(const id& y) const;
        bool operator<(const id& y) const;
        bool operator>(const id& y) const;
        bool operator<=(const id& y) const;
        bool operator>=(const id& y) const;
    
        template<class charT, class traits>
        friend std::basic_ostream<charT, traits>& 
        operator<<(std::basic_ostream<charT, traits>& os, const id& x);
    };
    
        2
  •  2
  •   Artyom    15 年前

    你有多少线?除非你有超过几百个,否则不太可能 unordered_map std::stringstream std::map . 别忘了 标准::地图 具有很小常数的对数复杂性。

    如果有数百个线程,那么应用程序可能有问题。

        3
  •  2
  •   antoxar    10 年前

    你为什么要继续使用字符串?你可以用

    size_t operator()(const boost::thread::id& id)
    {   
        using boost::hash_value;
    
        return hash_value(id);
    }
    
        4
  •  0
  •   Rob Kennedy    15 年前

    std::ostringstream 然后把这些杂凑起来 str() 结果。尽管输出格式未指定,但它对于给定的ID是唯一的,对于给定的程序运行也是一致的(只要线程ID仍然有效)。