c++ - C++ bimap 是否可以在视图的一侧具有与视图值的另一侧不同的键?怎么做?
问题描述
一开始我需要一张地图,所以我使用了std::map。
然后,添加了一些要求,我还需要获取“值”的“键”(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 存储一个数字,并且从右侧视图我需要能够调用<bimap>.righ.find(bar)
并获取成对的(foo + number stored for foo),但我仍然希望能够打电话<bimap>.left.find(foo)
和得到吧。
如何做到这一点?如果可能的话,我更喜欢一些现代 C++ 而不是 boost,但我想如果没有 boost,就很难拥有 bimap 功能。
编辑:我应该注意尺寸很重要,所以我不想存储任何涉及的部分两次,速度也很重要。
我应该有类似
"foo1"+100 <-> "bar1"
and
的东西"foo2"+300 <-> "bar4"
。
我希望能够调用<bimap>.left.find("foo1")
并获取“bar1”,
但也可以<bimap>.right.find("bar1")
获取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