C ++ bimap是否可以在视图的一侧具有与视图值的另一侧不同的键?怎么做? [英] Is C++ bimap possible with one side of view having different key than other side of the view value? How to do that?

查看:116
本文介绍了C ++ bimap是否可以在视图的一侧具有与视图值的另一侧不同的键?怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一开始我需要一张地图,所以我使用了std :: map.
然后,添加了一些要求,我还需要获取值"的键"(bars的foos),所以我使用了

At the beginning I needed a map, so I used std::map.
Then, some requirements were added and I needed to also get "keys" for "value" (foos for bar), so I used

boost::bimaps::bimap<
  boost::bimaps::unordered_set_of<boost::bimaps::tagged<std::string, foo>>, 
  boost::bimaps::multiset_of<boost::bimaps::tagged<std::string, bar>>>

然后,添加了一些其他要求,因此现在我需要为每个foo存储一个数字,并且从右侧视图中,我需要能够调用<bimap>.righ.find(bar)并获取(foo +为存储的数字对foo),但我仍然希望能够调用<bimap>.left.find(foo)并获得bar.

And after that, some more requirements were added, so now I need to store a number for every foo and from the right side view I need to be able to call <bimap>.righ.find(bar) and get pairs of (foo + number stored for foo), but I still want to be able to call <bimap>.left.find(foo) and get bar.

如何实现?如果可能的话,我更喜欢一些现代的C ++,而不是boost.

How to achieve that? I would prefer some modern C++ over boost if possible, but I guess it is harder to have bimap functionality without the boost.

我应该注意大小很重要,所以我不想存储任何涉及两次的零件,速度也很重要.

I should note that size matters, so I don't want to store any part involved twice and the speed also matters.

我应该有类似
"foo1"+100 <-> "bar1""foo2"+300 <-> "bar4".
我希望能够调用<bimap>.left.find("foo1")并获取"bar1",
还要<bimap>.right.find("bar1")并获取pair("foo1",100).

I should have something like
"foo1"+100 <-> "bar1" and "foo2"+300 <-> "bar4".
and I want to be able to call <bimap>.left.find("foo1") and get "bar1",
but also <bimap>.right.find("bar1") and get pair("foo1", 100).

推荐答案

#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

这篇关于C ++ bimap是否可以在视图的一侧具有与视图值的另一侧不同的键?怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆