I have a bimap like this:
using MyBimap = boost::bimaps::bimap<
boost::bimaps::unordered_set_of<A>,
boost::bimaps::unordered_set_of<B>>;
I want to construct it from a static initializer list, as it can be done for std::map
:
MyBimap map{{a1, b1}, {a2, b2}, {a3, b3}};
Unfortunately, it doesn't work because bimap
doesn't support initializer lists, so I tried a workaround. Boost's documentation lists the following constructors:
bimap();
template< class InputIterator >
bimap(InputIterator first,InputIterator last);
bimap(const bimap &);
So I tried the second one, like this:
std::vector<std::pair<A,B>> v{{a1, b1}, {a2, b2}, {a3, b3}};
MyBimap map(v.begin(), v.end());
It also didn't work. The documentation isn't exactly clear what kind of iterators this constructor expects, but apparently it's not simply an iterator of std::pair<A, B>
objects. Then what does this constructor expect for this kind of bimap?
I use the following "factory function" that takes a braced initializer list and returns a boost::bimap
:
template <typename L, typename R>
boost::bimap<L, R>
makeBimap(std::initializer_list<typename boost::bimap<L, R>::value_type> list)
{
return boost::bimap<L, R>(list.begin(), list.end());
}
Usage:
auto myBimap = makeBimap<int, int>({{1, 2}, {3, 4}, {5, 6}});
C++ beginner here: You can use boost::assign to generate the initialization. I found this solution here.
Example:
#include <boost/bimap.hpp>
#include <boost/assign.hpp>
//declare the type of bimap we want
typedef boost::bimap<int, std::string> bimapType;
//init our bimap
bimapType bimap = boost::assign::list_of< bimapType::relation >
( 1, "one" )
( 2, "two" )
( 3, "three" );
//test if everything works
int main(int argc, char **argv)
{
std::cout << bimap.left.find(1)->second << std::endl;
std::cout << bimap.left.find(2)->second << std::endl;
std::cout << bimap.left.find(3)->second << std::endl;
std::cout << bimap.right.find("one")->second << std::endl;
std::cout << bimap.right.find("two")->second << std::endl;
std::cout << bimap.right.find("three")->second << std::endl;
/* Output:
* one
* two
* three
* 1
* 2
* 3
*/
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With