Boost logo

Boost :

Subject: Re: [boost] std::map::find() wrapper
From: Olaf van der Spek (ml_at_[hidden])
Date: 2011-04-30 08:55:18


On Wed, Apr 20, 2011 at 9:14 PM, Denis Shevchenko
<for.dshevchenko_at_[hidden]> wrote:
> 20.04.2011 18:54, Olaf van der Spek пишет:
>>
>> Hi,
>>
>> I've written a small wrapper for std::map::find() (and map-like
>> containers/ranges) that returns a pointer to the value if found (or
>> NULL if not found).
>>
>> See https://svn.boost.org/trac/boost/ticket/5227
>>
>> The advantage is that you don't need the container type name (for
>> ::reference), you can initialize the pointer inside an if condition,
>> you don't have to compare against ::end() and you don't have to use
>> ->second.
>
> Hmm... Why not use map::at()?
>
> Compare:
>
> if (very_long_type_name_t::mapped_type* i = find_ptr(very_long_name, 1))
> cout << *i << "\n";
>
> with:
>
> try {
> cout << very_long_name.at( 1 ) << endl;
> } catch ( const std::exception& /* exc */ ) {
> cout << "No value with key 1" << endl;
> }
>
> You don't like exceptions?

IMO exceptions are for exceptional cases. Not finding an element is
not an exceptional case.

Your variant is also a lot longer / more complex, especially if you
want to store the returned reference.

Olaf


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk