Convert for loop to std::transform

Flaviu_ 971 Reputation points
2021-02-18T13:15:31.987+00:00

I have the following code:

for (auto it = _collection.cbegin(); it != _collection.cend(); ++it)
{
_values.emplace((*it)->Validate());
}

where:

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

and

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.

C++
C++
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,723 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 117.3K Reputation points
    2021-02-18T14:31:13.767+00:00

    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
    2021-02-19T15:23:13.36+00:00

    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.