问题
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>>>
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.
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.
EDIT: I should note that size matters, so I don't want to store any part involved twice and the speed also matters.
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).
回答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();
}
Output:
bar
bar
1
foo
0
bar
1
来源:https://stackoverflow.com/questions/50684467/is-c-bimap-possible-with-one-side-of-view-having-different-key-than-other-side