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?

本文关键字:视图 是否 bimap C++      更新时间:2023-10-16

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

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)并获取酒吧。

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

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

我应该有类似
"foo1"+100 <-> "bar1""foo2"+300 <-> "bar4".
我希望能够调用<bimap>.left.find("foo1")并得到"bar1",
但也<bimap>.right.find("bar1")并得到对("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