This question has been asked before here I admit, but it's now 4 years ago so I dare to ask for an update:
I need a way to add a tuple/pair to a container and search for both - the left and the right element efficiently.
Boost has bimap
and multi_index
which do exactly what I want but I wonder what's the recommended alternative in plain modern C++-11/14 in case you don't want to introduce a dependency to boost (for whatever reasons).
One answer in the linked suggests that there's no need for s.th. like a bimap any more due to transparent comparators. The accepted answer suggests an implementation combining std::map
s to both key1
-> key2
and key2
-> key1
.
I don't really know how the transparent comparators help me here and I'm just curious whether there is some this is how you should do it and why - solution. Can you provide some hints/links?
I think it's just a lot of tedious work.
For fun, I set out to implement a starting point here.
Live On Coliru
Notes:
std::list<tuple<K,V>>
. This makes sure that the iterator/reference invalidation semantics are as close tostd::map
as possiblestd::reference_wrapper<value_type const>
so we only index the first container, reallyI've only implemented the simple queries (
lower_bound
,upper_bound
,equal_range
andfind
). Of course iterators and ranged-for are there.You'll have some bits left to do (
erase
,emplace
, range-insertion, initializer_list construction; stateful allocator/comparator support is sketchy (no constructors take the relevant arguments) but scoped allocators have been taken into account.)Without further ado:
Prints: