Boost logo

Boost Users :

Subject: Re: [Boost-users] [lambda] Defining a predicate for std::find_if if the key to a std::map is std::pair
From: Anthony Foglia (AFoglia_at_[hidden])
Date: 2009-09-24 14:38:06


Nat Goodspeed wrote:
> Ryan McConnehey wrote:
>
>>> std::pair<cMap::iterator, bool> inserted =
>>> myMap.insert(cMap::value_type(cMap::key_type(givenName, properInt),
>>> cmap::mapped_type()));
>>> if (! inserted.second) // oh, it already existed?
>>> {
>>> ...
>>> }
>>
>> Since I'm using both givenName and properInt as a key, the insert will
>> never return false for just a duplicate of givenName.
>
> Forgive me if this is a stupid question, but if you don't want to
> compare the int, why is it part of the key at all?

He wants to compare the int upon retrieval, but it doesn't matter for
insertion. But I think he'd be better off getting the map to only care
about the string.

He can pass a custom less functor class as the third template parameter
to the map. Something like:

class LessFirstOfPair {
   bool operator(const pair<string, int> & x,
                 const pair<string, int> & y) {
     return x.first < y.first;
   }
}

typedef pair<string, int> cPair;
typedef map<cPair, vector<classA>, LessFirstOfPair> cMap;
cMap myMap;

Then he can enforce the check on the int upon retrieval. (The above has
not been checked at all for syntax errors.)

Or, even easier, make the key just the string and the value a pair of
the int and the vector of classA:

typedef map<string, pair<int, vector<classA> > cMap;

-- 
Anthony Foglia
Princeton Consultants
(609) 987-8787 x233

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