06. C++ Range-for statement

Posted by Yulai Blog on November 6, 2015

Range-for statement

  • boost style
    • BOOST_FOREACH iterates over sequences
    • a macro that simulates the std::foreach from C++11
  
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/array.hpp>

void boost_array()
{
    boost::array<int, 4> a = {1, 2, 3, 4};
    
    BOOST_FOREACH(int i, a)
    {
        std::cout << i;
    }
}
#include <iostream>
#include <array>

void cpp_11_foreach()
{
    std::array<int, 4> a = {11, 22, 33, 44};

    for (auto i:a)
    {
        std::cout << i;
    }
    
    //  Another example with Initializer lists:
    for (const auto x : { 1,2,3,5,8,13,21,34 }) cout << x << '\n';
}