From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2024-12-21 13:16:51


On 12/21/24 15:11, Peter Dimov via Boost wrote:
> Christian Mazakas wrote:
>> I'm with Andrey, I think the iterator API *is* the useful API. Typically, when I
>> find something in a map, I'll either erase or do something else where reusing
>> the iterator is a key part of everything.
>>
>> My whole thing was about what users actually wanted vs all the costs of
>> everything else.
>
> What this user has always wanted is to not have to write this:
>
> auto it = map.find( key );
> if( it != map.end() )
> {
> // do something with it->second
> }
>
> That's why I'm always defining a helper function `lookup` that returns a
> pointer, which allows me to write this instead:
>
> if( auto p = lookup( map, key ) )
> {
> // do something with *p
> }

I'll note that with C++17 you can also write this:

  if ( auto it = map.find( key ); it != map.end() )
  {
    // do something with it->second
  }

But each of the three variants seem pretty much equivalent to me, from
the code clarity standpoint.