All lessons

Power Tools: auto, Lambdas & <algorithm>

10 min · C++

Skip repeating types with auto, write inline lambdas, and transform vectors with <algorithm>.

C++ · Power Tools: auto, Lambdas & <algorithm>0/5 cleared

Enemy 1 of 5

auto and range-based for

This loops over every number in the vector and prints each one, with auto letting the compiler pick the type. Press Run to see 1 2 3.

Why this works

Writing out full types like vector<string>::iterator gets verbose fast, so C++ gives you auto: put auto where a type would go, and the compiler figures out the actual type from the value you're assigning. It doesn't make C++ dynamically typed: the type is still fixed and checked at compile time, auto is purely a shorthand so you don't have to spell it out yourself.

A range-based for loop, written for (auto n : container), walks every element of a container (a vector, a map, an array) one at a time without you managing an index variable at all. It's the cleanest way to say "do this for each item" when you don't need to know the position of each item.

You
Binary Treant
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.