Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Modern C++ Programming Cookbook

You're reading from   Modern C++ Programming Cookbook Recipes to explore data structure, multithreading, and networking in C++17

Arrow left icon
Product type Paperback
Published in May 2017
Publisher Packt
ISBN-13 9781786465184
Length 590 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Marius Bancila Marius Bancila
Author Profile Icon Marius Bancila
Marius Bancila
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Learning Modern Core Language Features FREE CHAPTER 2. Working with Numbers and Strings 3. Exploring Functions 4. Preprocessor and Compilation 5. Standard Library Containers, Algorithms, and Iterators 6. General Purpose Utilities 7. Working with Files and Streams 8. Leveraging Threading and Concurrency 9. Robustness and Performance 10. Implementing Patterns and Idioms 11. Exploring Testing Frameworks 12. Bibliography

Using range-based for loops to iterate on a range

Many programming languages support a variant of a for loop called for each, that is, repeating a group of statements over the elements of a collection. C++ did not have core language support for this until C++11. The closest feature was the general purpose algorithm from the standard library called std::for_each, that applies a function to all the elements in a range. C++11 brought language support for for each that is actually called range-based for loops. The new C++17 standard provides several improvements to the original language feature.

Getting ready

In C++11, a range-based for loop has the following general syntax:

    for ( range_declaration : range_expression ) loop_statement

To exemplify the various ways of using a range-based for loops, we will use the following functions that return sequences of elements:

    std::vector<int> getRates() 
{
return std::vector<int> {1, 1, 2, 3, 5, 8, 13};
}

std::multimap<int, bool> getRates2()
{
return std::multimap<int, bool> {
{ 1, true },
{ 1, true },
{ 2, false },
{ 3, true },
{ 5, true },
{ 8, false },
{ 13, true }
};
}

How to do it...

Range-based for loops can be used in various ways:

  • By committing to a specific type for the elements of the sequence:
        auto rates = getRates();
for (int rate : rates)
std::cout << rate << std::endl;
for (int& rate : rates)
rate *= 2;
  • By not specifying a type and letting the compiler deduce it:
        for (auto&& rate : getRates()) 
std::cout << rate << std::endl;

for (auto & rate : rates)
rate *= 2;

for (auto const & rate : rates)
std::cout << rate << std::endl;
  • By using structured bindings and decomposition declaration in C++17:
        for (auto&& [rate, flag] : getRates2()) 
std::cout << rate << std::endl;

How it works...

The expression for the range-based for loops shown earlier in the How to do it... section is basically syntactic sugar as the compiler transforms it into something else. Before C++17, the code generated by the compiler used to be the following:

    { 
auto && __range = range_expression;
for (auto __begin = begin_expr, __end = end_expr;
__begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}

What begin_expr and end_expr are in this code depends on the type of the range:

  • For C-like arrays, __range and __bound are the number of elements in the array.
  • For a class type with begin() and end() members (regardless of their type and accessibility): __range.begin() and __range.end().
  • For others it is begin(__range) and end(__range) that are determined via argument dependent lookup.

It is important to note that if a class contains any members (function, data member, or enumerators) called begin or end, regardless of their type and accessibility, they will be picked for begin_expr and end_expr. Therefore, such a class type cannot be used in range-based for loops.

In C++17, the code generated by the compiler is slightly different:

    { 
auto && __range = range_expression;
auto __begin = begin_expr;
auto __end = end_expr;
for (; __begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}

The new standard has removed the constraint that the begin expression and end expression must have the same type. The end expression does not need to be an actual iterator, but it has to be able to be compared for inequality with an iterator. A benefit of this is that the range can be delimited by a predicate.

See also

  • Enabling range-based for loops for custom types
You have been reading a chapter from
Modern C++ Programming Cookbook
Published in: May 2017
Publisher: Packt
ISBN-13: 9781786465184
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime