gpt4 book ai didi

c++ - 使用键属性 vector boost 多索引

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

我有一个看起来像这样的类(简化):

class DataObject {
public:
int getId() const;
const std::vector<int>& getAccounts() const;
};

我需要一个由 id 索引的对象的关联数组( HashMap )及其适用的所有帐户。 IE。我需要查找所有 DataObject适用于特定帐户的实例(而单个 DataObject 可以适用于多个帐户)。

我首先想到的是使用 boost::multi_index_contatiner由两者索引。但是,我不知道如何为该对象创建所有帐户的索引,我不确定这是否可行。

我的开头是这样的:

struct tags
{
struct id;
struct account;
};

typedef boost::multi_index_container<
const DataObject*,
boost::multi_index::indexed_by<
// index by the rule id (replacement, removal)
boost::multi_index::hashed_unique<
boost::multi_index::tag<tags::id>,
boost::multi_index::const_mem_fun<DataObject, int, &DataObject::getId>
>,
// index by the account
boost::multi_index::hashed_non_unique<
boost::multi_index::tag<tags::account>,
???
>
>
> DataMap_t;

而且我不知道应该用什么来代替 ???提取单个特定帐户。回顾一下,我不想按帐户的 vector 索引(我知道该怎么做),我需要按 vector 中的每个帐户索引 .

到目前为止,我实际上创建了一个单独的 boost::unordered_map<int, const DataObject*> ID 的索引和另一个单独的 boost::unordered_multimap<int, const DataObject*>帐户的索引,然后我遍历所有帐户并为每个帐户存储一个值(对于删除也是如此)。但我想知道是否有更简单的方法,最好是使用 boost::multi_index_container .

最佳答案

你需要的是一个关系表。

您也可以使用 Boost Bimap(对我来说似乎更容易):

The following code creates an empty bimap container:

typedef bimap<X,Y> bm_type; 
bm_type bm;

Given this code, the following is the complete description of the resulting bimap.

  • bm.left is signature-compatible with std::map
  • bm.right is signature-compatible with std::map
  • bm is signature-compatible with std::set< relation >

使用 Multi-Index 我建议将关系存储在对象之外:

struct Data { int id; };
struct Account { int id; };

struct Relation { int data_id, account_id; };

using Table = boost::multi_index_container<Relation,
bmi::indexed_by<
bmi::ordered_unique<
bmi::tag<struct by_data>,
bmi::member<Relation, int, &Relation::data_id>
>
bmi::ordered_non_unique<
bmi::tag<struct by_account>,
bmi::member<Relation, int, &Relation::account_id>
>
>
>;

如果您注意对象生命周期和引用稳定性,您可以更方便调用者:

struct Data { int id; };
struct Account { int id; };

struct Relation {
std::reference_wrapper<Data const> data;
std::reference_wrapper<Account const> account;

int data_id() const { return data.get().id; }
int account_id() const { return account.get().id; }
};

using Table = boost::multi_index_container<Relation,
bmi::indexed_by<
bmi::ordered_unique<
bmi::tag<struct by_data>,
bmi::const_mem_fun<Relation, int, &Relation::data_id>
>
bmi::ordered_non_unique<
bmi::tag<struct by_account>,
bmi::const_mem_fun<Relation, int, &Relation::account_id>
>
>
>;

关于c++ - 使用键属性 vector boost 多索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40039526/

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