|
Boost Users : |
Subject: Re: [Boost-users] [bimap] Creating a bimap fom a std::map
From: Edward Diener (eldiener_at_[hidden])
Date: 2009-11-25 13:24:42
Matias Capeletto wrote:
> 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());
My opinion is that you should have a constructor which takes a std::map,
where the types of the map are the types of the bimap. If the types of
the map are the same as the types of the bimap, then the constructor
should do exactly the equivalent to what you show just above. If the
types of the map are the reverse of the types of the bimap, then the
constructor should be the equivalent of:
std::map<std::string,int> myMap;
// ... fill myMap
boost::bimap<int,std::string> myBimap;
myBimap.right.insert(myMap.begin(),myMap.end());
This is an ease of use issue and I really do not see why you can not
make the use of bimap easier to use in this way. Especially since you
also agree that this is a very common scenario. Can I really be the
first person who has suggested this regarding bimap ?
Nonetheless thanks for pointing out to me how it is done.
>
> 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());
Yes, of course. See above. I just do not agree that not providing the
obvious constructor is good because it "maintains symmetry". Many things
in programming are good because they provide ease-of-use and my
suggestion is an obvious case of that.
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