c++c++11foreachcontainersranged-loops

Is statement in for each loop executed each iteration?


I have a function which returns a container. Let's just call it 'Container'.

Container GenerateRandomContainer() { ... }

This function will generate a container with random elements that are different each call.

When I iterate through this container using a for each loop like this:

for(Element e : GenerateRandomContainer()) { ... }

Will it generate a new Container each iteration or will it generate only one when the for each loop is entered?


Solution

  • The range-based for loop is equivalent as follows:

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

    Note the 1st statement auto && __range = range_expression ; (range_expression will be GenerateRandomContainer() for your code); that means the Container will be generated only once, and iterates on all the elements of it.