Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to simplify this expression?

Tags:

c++

c++11

stl

Lets say I have a class with a member variable:

std::unordered_map<KeyType, std::shared_ptr<ValueType>> myMap

and in a member function I want to do the following:

std::for_each(myMap.begin(), myMap.end(), [](std::pair<const KeyType, std::shared_ptr<ValueType>>& pair){pair.second->someMethod(); });

Is there anyway to shorten the lambda expression? I thought I could do this but it was not valid syntax:

std::for_each(myMap.begin(), myMap.end(), [](decltype(myMap::valueType)& pair){pair.second->someMethod(); });
like image 891
grivescorbett Avatar asked Apr 28 '12 17:04

grivescorbett


1 Answers

I wouldn’t bother with a lambda at all. Unlike the other standard algorithms, for_each() is not any more expressive or readable than the equivalent for.

for (auto& p : myMap)
    p.second->someMethod();

for (auto p = myMap.begin(); p != myMap.end(); ++p)
    p->second->someMethod();
like image 150
Jon Purdy Avatar answered Sep 30 '22 17:09

Jon Purdy