Pragmatic Advice for C++11’s Range-For

C++ is known to be a programming language that offers several options for doing stuff, and with all the options available for range-based for loops, sometimes folks (especially beginners) get confused.

My pragmatic piece of advice for C++11’s range-based for loops is:

  1. If you are observing the items in the container, use “const auto&”.
  2. If you are modifying the items in place during the iteration, use “auto&”.

That’s as simple as that!

In code:

// Observe elements
for (const auto& elem : container)

// Modify elements in place
for (auto& elem : container)

A more detailed discussion can be found on StackOverflow (this includes also some special corner-cases, like proxy iterators as in std::vector<bool>, or auto&& in generic code):

“What is the correct way of using C++11’s range-based for?”

P.S.
I’ve also seen some code with const auto&& used in range-for, but that doesn’t seem to make sense.

Pluralsight Blog Post: Simplifying Lexicographical Comparisons with C++11

A C++ article of mine has been published on the Pluralsight blog. It shows how to pragmatically use C++11’s std::tie to easily implement lexicographical comparisons of custom data types (the concept of lexicographical comparison is introduced in that post as well).

Basically, instead of writing a long (and potentially bug-prone) sequence of if statements, std::tie can be invoked to build tuples, which in turn can be compared using std::tuple’s already-defined operator< overload.

I also showed a common error that can happen when calling std::tie, and how to fix it using std::make_tuple.

An important take-away is that if there are tools already tested and available in the C++ standard library, it’s better to use them than attempting to reinvent the wheel writing boilerplate bug-prone “low-level” C++ code.

Check out the blog post here!

Thanks to Stephan T. Lavavej (Senior Library Developer at Microsoft Visual C++ Team) for technically reviewing this article.