Search code examples
c++boostc++11boost-bimap

How to construct Boost bimap from static list?


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?


Solution

  • 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;
    }