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: Nat Goodspeed (nat_at_[hidden])
Date: 2009-09-24 08:51:07


Roman Perepelitsa wrote:

> 2009/9/24 Ryan McConnehey <mccorywork_at_[hidden]
> <mailto:mccorywork_at_[hidden]>>
>
> I have the following std::map signature.
>
> typedef std::pair<std::string, int> cPair;
> typedef std::map<cPair, std::vector<classA> > cMap;
> cMap myMap;
>
> When entering values into the map, the std::string is the only part
> of the key that needs to be unique. Upon retrieving map values both
> values of the key need to be compared. I've tried to define my
> insert comparison as follows, but am uncertain how to define the
> predicate with boost::lambda.
>
> std::string givenName = "some_text_value";
> int givenInt = 3;
> cMap::const_iterator itor = std::find_if( myMap.begin(),
> myMap.end(), boost::lambda::bind( ??? , _1) == givenName );
>
>
> cMap::const_iterator itor =
> std::find_if(myMap.begin(), myMap.end(),
> boost::lambda::bind(&cMap::value_type::first, _1) ==
> givenName);
>
> Note that you can use std::map::find instead:
>
> cMap::const_iterator itor = myMap.find(givenName);

I'd endorse Roman's suggestion, maybe something like:

cMap::const_iterator itor =
     myMap.find(cMap::key_type(givenName, properInt));

You said "my insert comparison," as though perhaps if itor ==
myMap.end() you intend to follow up with an insertion. For such cases I
typically just code the insert() call:

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?
{
     ...
}

The latter form traverses the map structure just once, whether or not
there's an existing entry with this key value.


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