Is there an easier way than to define a lambda expression for this?
No.
Depends what you mean by easier. One important thing to remember here is that in C++, the value_type
of a std::map
is pair<const key_type,mapped_type>
and not just the mapped_type. std::map::iterator
iterates over this value_type
and you need a wrapper to fetch either the key or the mapped type.
All C++ Standard Library algorithms work on iterators and for std::map its an iterator to value_type. So for the algorithms to work on the mapped type, we need to re-map the value_type
to mapped type and for that either
- You need a helper named function (pre C++11)
- You would need a functor
- Or, You would need a lambda.
It is worth noting that
"C++ Standard Library algorithms would be much more pleasant to use if
C++ had support for lambdas"
A proposal to add lambda functions to the C++ standard, N1958=06-002.
So if you think your code looks ugly, your intention to cleanse the code would defeat the original motivation of lambda.
Thus, if you are intending to use C++ Standard Library algorithms, you need to use lambda if required as in the case of std::map (period).
Of-course you can still re-write using iterative manner but it is a matter of choice and readability and "readability lies in the eyes of the reviewers"