1

我有以下内容:

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”部分,而不是从左侧调用的方法查找和擦除的两个部分。如何做到这一点?我试图阅读 bimap 实现,但我仍然很难做到。

我已经问过更广泛的问题:C++ bimap 是否可能在视图的一侧具有与视图值的另一侧不同的键?怎么做? 并且从我必须覆盖的评论中operator <,但我什至不确定这是否足够。

4

2 回答 2

1

我会和boost::multi_index_container这里一起去boost::bimap

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视图

于 2018-06-05T13:28:18.783 回答
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

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

于 2018-06-05T20:54:50.900 回答