gpt4 book ai didi

c++ - multi_index 哈希唯一可选参数

转载 作者:搜寻专家 更新时间:2023-10-31 01:44:57 25 4
gpt4 key购买 nike

我有一个包含多个 hashed_unique 索引(A、B、C)的 multi_index。
并非所有对哈希的插入都包含所有索引的信息。一些索引可能是空的。有些可能包含所有条目。
我将它们定义为 hashed_unique,因为如果它不为空,它就是唯一的。
我可以将其定义为 hashed_non_unique,并将每个键放入一个包装器中,以判断键是否为空,如 Boost Multi_Index Question 中所建议的那样
但随后我将需要搜索每个键,然后再尝试插入/修改/替换以避免出现非唯一键的情况,这不是良好的性能解决方案。
有更好的解决方案吗?
如果我将所有索引都定义为 hashed_unique,它不会接受每个索引插入一个以上的空值。

例如:

(11,6,8)
(10,3,empty)
(empty,4,empty)
(empty,empty,1)

我使用的是 boost 1.49,多索引在共享内存中。

最佳答案

您可以使用以下包装器:

#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/functional/hash.hpp>

template<typename T>
class maybe
{
public:
maybe():impl(boost::make_shared<int>(0)){}
maybe(const T& t):impl(t){}

bool empty()const{return impl.which()==0;}
T& get(){return boost::get<T>(impl);}
const T& get()const{return boost::get<T>(impl);}

friend bool operator==(const maybe& x,const maybe& y){return x.impl==y.impl;}
friend std::size_t hash_value(const maybe& x){return boost::hash<impl_type>()(x.impl);}

private:
typedef boost::variant<boost::shared_ptr<void>,T> impl_type;

impl_type impl;
};

...

maybe<int> x=5;
maybe<int> y; // empty
maybe<int> z; // empty

maybe 的好处是空值是不同的(即示例中的 !(y==z)),因此您可以保留您的Boost.MultiIndex 索引唯一。

关于c++ - multi_index 哈希唯一可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22812910/

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