是否可以覆盖boost :: bimaps :: bimap.left的“find”和“erase”方法?怎么做?

时间:2018-06-05 12:28:21

标签: c++ key-value keyvaluepair bimap boost-bimap

我有以下内容:

struct foo_and_number_helper {
  std::string foo;
  uint64_t number;
};
struct foo_and_number {};
struct bar {};

using my_bimap = boost::bimaps::bimap<
  boost::bimaps::unordered_set_of<boost::bimaps::tagged<foo_and_number_helper, foo_and_number>>, 
  boost::bimaps::multiset_of<boost::bimaps::tagged<std::string, bar>>
>;

my_bimap instance;

我希望能够像这样调用查找和擦除方法:
instance.left.find("foo")代替instance.left.find({"foo",1})
instance.left.erase("foo")代替instance.left.erase({"foo",1})

我只想使用“foo_and_number_helper”的“foo”部分而不是两个部分,从左侧调用方法find和erase。怎么实现呢?我试图阅读bimap实现,但我仍然很难做到这一点。

我已经提出了更广泛的问题:Is C++ bimap possible with one side of view having different key than other side of the view value? How to do that? 我必须覆盖operator <的评论,但我对此并不确定,是否足够。

2 个答案:

答案 0 :(得分:1)

我会在此boost::bimapboost::multi_index_container

namespace bmi = boost::multi_index;

struct ElementType { 
  std::string foo; 
  std::string bar;
  uint64_t number; 
}

using my_bimap = boost::multi_index_container<
  ElementType,
  bmi::indexed_by<
    bmi::unordered_unique<
      bmi::tagged<struct Foo>, 
      bmi::member<ElementType, std::string, &ElementType::foo>
    >,
    bmi::ordered<
      bmi::tagged<struct Bar>, 
      bmi::member<ElementType, std::string, &ElementType::bar>
    >,
    // and others like
    bmi::sequenced<
      bmi::tagged<struct InsertionOrder>
    >
  >
>;

然后你会像

一样使用它
my_bimap instance;

instance.get<Foo>().find("foo");
instance.get<Bar>().erase("bar");
std::cout << instance.get<InsertionOrder>()[10].foo;

即。您没有leftright视图,而是拥有任意数量的观看次数

答案 1 :(得分:0)

所以我跟着@Caleth的回答并调整了它:

#include <boost/multi_index/hashed_index.hpp>
#include <boost/bimap/bimap.hpp>

using namespace std;

struct ElementType { 
  string foo; 
  string bar;
  uint64_t number; 
};

using namespace boost::multi_index;

using my_bimap = multi_index_container<
  ElementType,
  indexed_by<
    hashed_unique<member<ElementType, string, &ElementType::foo>>,
    ordered_non_unique<member<ElementType, string, &ElementType::bar>>
  >
>;

int main() {
  my_bimap instance;

  instance.insert({"foo", "bar", 0});
  instance.insert({"bar", "bar", 1});

  cout << instance.get<0>().find("bar")->foo << endl;
  cout << instance.get<0>().find("bar")->bar << endl;
  cout << instance.get<0>().find("bar")->number << endl;
  auto range = instance.get<1>().equal_range("bar");
  for (auto it = range.first; it != range.second; ++it) {
    cout << it->foo << endl;
    cout << it->number << endl;
  }

  cin.sync();
  cin.ignore();
}

输出:

bar
bar
1
foo
0
bar
1

是的,它没有回答我的问题,但我认为我实现了我想要的。