Convert for loop to std::transform

Flaviu_ 791 Reputation points

I have the following code:

for (auto it = _collection.cbegin(); it != _collection.cend(); ++it)


std::vector<std::unique_ptr<MyObject>>  _collection;
std::unordered_map<std::string, MyOtherObject> _values;


CMyObject has a method:

virtual std::pair<std::string, MyOtherObject> Validate() = 0;

My question is: how can I use std::transform instead of for ? I can use lambda too, no pb.

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,324 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 106.5K Reputation points

    I think that transform is not appropriate, but you can use for_each:

    std::for_each( _collection.cbegin( ), _collection.cend( ), 
       [&]( const auto& obj ) { _values.emplace( obj->Validate( ) ); } );

    or a for-each loop:

    for( const auto& obj : _collection ) _values.emplace( obj->Validate( ) );
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Igor Tandetnik 1,106 Reputation points

    If you really want std::transform, I think this would work (not tested):

    std::transform(_collection.cbegin(), _collection.cend(), std::inserter(_values, _values.end()),
      [](const std::unique_ptr<MyObject>& ptr) { return ptr->Validate(); });
    1 person found this answer helpful.
    0 comments No comments