Home > Software design >  c - how to list all keys inside a boost::bimap
c - how to list all keys inside a boost::bimap

Time:12-21

What would be a simple way to iterate through and store all keys of boost::bimap into a vector. Would it work just like we would for std::map

CodePudding user response:

This would be one way:

#include <boost/bimap.hpp>
#include <vector>

template<class L, class R>
std::vector<L> to_vector(const boost::bimap<L, R>& bm) {
    std::vector<L> rv;
    rv.reserve(bm.size());   // or bm.size() * 2 if you want to store the right keys too

    for(auto&[l, r] : bm) {  // loop through all the entries in the bimap
        rv.push_back(l);     // store the left key
        // rv.push_back(r);  // if you want to store the right key too
    }
    return rv;
}

Then calling it:

auto vec = to_vector(your_bimap);
  • Related