【问题标题】:Is C++ bimap possible with one side of view having different key than other side of the view value? How to do that?C++ bimap 是否可以在视图的一侧具有与视图值的另一侧不同的键?怎么做?
【发布时间】:2018-11-14 00:26:30
【问题描述】:

一开始我需要一张地图,所以我使用了std::map。
然后,添加了一些要求,我还需要获取“value”的“keys”(bar 的 foos),所以我使用了

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 存储一个数字,并且从右侧视图我需要能够调用 &lt;bimap&gt;.righ.find(bar) 并获得成对的 (foo + number stored for foo),但我仍然希望能够拨打&lt;bimap&gt;.left.find(foo) 并获得酒吧。

如何做到这一点?如果可能的话,我更喜欢一些现代 C++ 而不是 boost,但我想如果没有 boost,就很难拥有 bimap 功能。

编辑:我应该注意尺寸很重要,所以我不想存储任何涉及的部分两次,而且速度也很重要。

我应该有类似
"foo1"+100 &lt;-&gt; "bar1""foo2"+300 &lt;-&gt; "bar4".
我希望能够致电&lt;bimap&gt;.left.find("foo1") 并获得“bar1”,
还有&lt;bimap&gt;.right.find("bar1") 并得到pair("foo1", 100)。

【问题讨论】:

  • 把数字放到foo里?创建 foo->number 的新映射?
  • 对不起,我添加了一条注释,我不想将 foos 存储两次。我想将数字添加到 foo 中,但后来我意识到我希望能够在没有数字的情况下搜索 foo 并获得 bar。
  • "搜索没有数字的 foo 并得到 bar。" 好的 - 所以创建一个具有可选数字的 foo 版本;在 operator &lt; 中被忽略(或 boost::bimap 使用的任何一个)
  • 我认为 boost multiindex 会是一个更好的选择。
  • @UKMonkey 我正在考虑类似的事情。您的意思是像创建一个带有 string 和 int 的结构并覆盖 operator

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


【解决方案1】:
#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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 2020-02-21
    • 1970-01-01
    • 2013-12-30
    • 2015-12-16
    • 2013-04-03
    • 1970-01-01
    相关资源
    最近更新 更多