How to construct Boost bimap from static list?
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}});
The iterator begin/end should be for a sequence of bimap values.
boost::bimap< A, B>::value_type
A bimap value is a lot like a std::pair and can be initialized with {a1, b1}
syntax. A vector of them seems to work too, which provides usable iterators for the constructor.
Ok, here is an example that compiles and runs for me (gcc 4.8.2 --std=c++11)
#include <vector>
#include <boost/bimap.hpp>
using namespace std;
int main() {
typedef boost::bimap< int, int > MyBimap;
std::vector<MyBimap::value_type > v{{1, 2}, {3, 4}, {5, 6}};
MyBimap M(v.begin(),v.end());
std::cout << "The size is " << M.size()
<< std::endl;
std::cout << "An entry is 1:" << M.left.at(1)
<< std::endl;
}
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
*/
}