我开始使用 unordered_set
来自 tr1
的类(class)命名空间以 boost 对普通(基于树的)STL 的访问 map
.但是,我想在 boost ( boost::thread::id
) 中存储对线程 ID 的引用,并意识到这些标识符的 API 非常不透明,您无法清楚地获得它的哈希值。
令人惊讶的是,boost 实现了 tr1
的部分内容(包括 hash
和 unordered_set
),但它没有定义能够散列线程 ID 的散列类。
查看 boost::thread::id
的文档我发现线程 ID 可以输出到流中,所以我的散列解决方案是这样的:
struct boost_thread_id_hash
{
size_t operator()(boost::thread::id const& id) const
{
std::stringstream ostr;
ostr << id;
std::tr1::hash<std::string> h;
return h(ostr.str());
}
};
也就是说,将其序列化,将散列应用于生成的字符串。然而,这似乎比实际使用 STL 效率低 map<boost::thread::id>
.
那么,我的问题是:您找到更好的方法了吗? boost 和 tr1 不强制存在 hash<boost::thread::id>
是否明显不一致?类(class)?
谢谢。
最佳答案
字符串化的开销 thread::id
(仅在之后计算字符串哈希)就像您自己说的那样,与任何性能优势相比是天文数字 tr1::unordered_map
可能会授予 std::map
.所以简短的回答是:坚持使用 std::map< thread::id, ... >
如果您绝对必须使用无序容器,尝试使用native_handle_type
而不是 thread::id
如果可能的话,即更喜欢 tr1::unordered_map< thread::native_handle_type, ... >
, 调用 thread::native_handle()
而不是 thread::get_id()
什么时候insert
荷兰国际集团和find
ing.
请勿尝试以下行为:
struct boost_thread_id_hash {
// one and only member of boost::thread::id is boost::thread::id::thread_data
// of type boost::detail::thread_data_ptr;
// boost::thread::id::operator==(const id&) compares boost::thread::id::thread_data's
size_t operator()(boost::thread::id const& id) const {
const boost::detail::thread_data_ptr* pptdp = \
reinterpret_cast< boost::detail::thread_data_ptr* >(&id);
return h(pptdp->get());
}
};
它可以工作,但非常脆弱,几乎是一颗定时炸弹。它假定对 thread::id
的内部运作有深入的了解。执行。它会让您受到其他开发人员的诅咒。如果可维护性有任何问题,请不要这样做!连补丁boost/thread/detail/thread.hpp
添加size_t hash_value(const id& tid)
作为thread::id
的 friend 更好”。 :)
关于c++ - tr1::hash 用于 boost::thread::id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/772192/