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 12:35:17


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?

> Also, if the
> insert did return false then it means a good value at that map key has
> been replaced. The reason I'm trying to catch this duplication is
> because "last value entered wins" doesn't meet the requirement I was given.

Not true. When insert() finds an existing key, it returns a std::pair
with the iterator to that entry and 'false' meaning it wasn't newly
inserted. Per Stroustrup:

"The operation m.insert(val) attempts to add a (Key, T) pair val to m.
Since maps rely on unique keys, insertion takes place only if there is
not already an element in the m with that key. The return value of
m.insert(val) is a pair<iterator, bool>. The bool is true if val was
actually inserted. The iterator refers to the element of m holding the
key k."

...

"In fact, [] is little more than a convenient notation for insert(). The
result of m[k] is equivalent to the result of
(*(m.insert(make_pair(k,V())).first)).second, where V() is the default
value for the mapped type."


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