I have been talking with my colleague about traversing std::map and we both agree that using first-second attributes as a key-value pair is not the most readable solution.

It is not so bad but we would like to write something like this:


I found a way of writing code similar to that:

In C++14 it could be rewritten like this:

How it is implemented? Pretty simple:

Expert question?

How can we make this code even more generic (ie. handling tuple’s with variable length of elements)? Some type_traits? Concepts? What do you think?


Service Delivery Manager and Scrum Master at Sii Poland company.

Since 2007 C++ enthusiast. C++11/14 evangelist - learn modern ways of developing in C++. Teaching TDD and agile way of coding.

  • googleplus
  • linkedin
  • twitter

2 comments on “Readable for_each loop for maps

  • Your solution definitely helps readability, but sacrifices writing generic code as you’ve defined an entirely new algorithm which is specific to maps. We can get nearly the same benefits and use the existing for_each() algorithm by thinking a little more “functionally”: This solution can be used with existing code that calls into for_each() and allows the calling code to pass in a custom predicate!

    (It’s a few more characters of typing, but I sadly I couldn’t think of a shorter name which still conveys its intentions.)

    Unfortunately, to keep the implementation this short requires C++14, but I’m fairly certain this can be done in C++11 with a bit more boilerplate (function traits aught to do it).

Leave a Reply