Boost logo

Boost Users :

Subject: Re: [Boost-users] [bimap] Creating a bimap fom a std::map
From: Matias Capeletto (matias.capeletto_at_[hidden])
Date: 2009-11-25 12:43:04


Hello Edward,

On Wed, Nov 25, 2009 at 10:40 AM, Edward Diener <eldiener_at_[hidden]> wrote:
> I would have thought, naively enough, that one of the common uses of a bimap
> was that one should be able to create a bimap from a std::map as long as the
> relation between the two types was unique both ways.

Yes, this is a very common scenario.

> I was disconcerted when
> I did not see a bimap constructor that accepted a std::map of the same
> types,

The library does not have this constructor by design. A bimap can be
viewed as a map (if you choose the left or the right view) but it is
not directly compatible with a map to enforce the idea that both
values are at the same level in the container. You explicitly have to
choose the left view to do what you are trying to achieve:

  std::map<int,std::string> myMap;
  // ... fill myMap
  boost::bimap<int,std::string> myBimap;
  myBimap.left.insert(myMap.begin(),myMap.end());

The extra line helps to maintain the symmetry, and I think that in the
end makes the code less cryptic. Imagine now that you have the data in
a reverse map, you should write something along the following lines:

  std::map<std::string,int> myRMap;
  // ... fill myMap
  boost::bimap<int,std::string> myBimap;
  myBimap.right.insert(myRMap.begin(),myRMap.end());

I hope that this works for you.
Best regards
Matias


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net