如何使用boost::multi_index复合密钥

How to use boost::multi_index composite keys

本文关键字:index 复合 密钥 multi 何使用 boost      更新时间:2023-10-16

我的需求需要这样的映射:

pair<string key1, string key2> _keypair;
map<_keypair, shared_ptr<classX>>

我的需求是:

  1. key1和key2对必须是唯一的。

  2. 我应该能够使用key1和Key2对进行访问。

  3. 插入。

  4. 使用复合密钥删除

我遇到了boost::multi_index,但不太清楚。有人能给我举个例子说明我的情况吗?

smth是这样的(我没有编译这个代码):

struct value_type
{
    std::string key1_;
    std::string key2_;
    std::shared_ptr<some_class> ptr_;
};
// index tags (otherwise you have to use number when get<N>() corresponding index)
struct composite_index;
struct key1_index;
struct key2_index;
using namespace boost::multi_index;
typedef multi_index_container<
    value_type
  , indexed_by<
        ordered_unique<
            tag<composite_index>
          , composite_key<
                value_type
              , member<value_type, std::string, &value_type::key1_>
              , member<value_type, std::string, &value_type::key2_>
              >
          >
      , ordered_non_unique<
            tag<key1_index>
          , member<value_type, std::string, &value_type::key1_>
          >
      >
      , ordered_non_unique<
            tag<key2_index>
          , member<value_type, std::string, &value_type::key2_>
          >
      >
  > index_type;
index_type a;
a.insert({"key-1", "key-2", std::shared_ptr<some_class>(new some_class(...)});
// find by key1_index (or key2_index)
auto range = a.get<key1_index>().equal_range("key-1");
// find by composite index
auto it = a.get<composite_index>().find(std::make_tuple("key-1", "key-2"));
// erase by any iterator type
a.erase(it);