The obvious way to convert a bimap to std::map, doesnt seem to work. Is below the correct/good way to convert? Is there a better/shorter way?
typedef boost::bimap<int, std::string> MapType;
MapType _bimap;
//Fill _bimap
MapType::left_map& lmap = _bimap.left;
//std::map<int, std::string> bmap(lmap.begin(), lmap.end()); //THIS DOESNT WORK
std::map<int, std::string> bmap;
BOOST_FOREACH(MapType::left_const_reference entry, lmap)
{
bmap[entry.first] = entry.second;
}
The values from a
bimap
cannot be directly assigned to thos of amap
because there is a problem of type (ignoring the more obvious problem of const-ness of the value):(source)
And :
That means that there is no guarantee that your bimap value_type is assignable or copyable to a map value_type. In fact it is not:
That will fail horribly (same kind of thing if you try
t2 = t1;
)So either you find a way to convert your value_types either you keep with a for_each/transform/copy ... idiom.
There is a neat solution signaled here in comment by @CharlesPehlivanian (that he will maybe provide as an answer also), that is to use
boost::trasnform_iterator
.For that you have to provide a
transformer
functor (it does not work with a raw lambda, you have to use a struct withoperator()
andresult_type
or astd::function
) that will convert the input iterator value to the output one:Then you just have to wrap begin and end iterator with
boost::make_transform_iterator
:Here is the whole code:
http://coliru.stacked-crooked.com/a/8fae0d47ca4b72a1