Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer list in a range for loop

I have objects of different types derived from a single super-type. I wonder if there are any disadvantages in using std::initializer list in a range for loop like this:

for(auto object: std::initializer_list<Object *>{object1, object2, object3}) {
}

Is it completely OK and efficient or would it be better to use an array? To me the std::array solution seems to be more restrictive for the compiler and there is a disadvantage of explicitly stating the size:

for(auto object: std::array<Object*, 3>{object1, object2, object3}) {
}

Is there any other or nicer way of iterating over an explicitly given list of objects?

like image 620
Juraj Blaho Avatar asked Mar 05 '14 08:03

Juraj Blaho


People also ask

What is a ranged based for loop?

Range-based for loop in C++It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

What is use of auto in for loop?

Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression. range-expression − any expression used to represent a sequence of elements.

What is std :: Initializer_list?

An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .

Does C++ have range function?

Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .


1 Answers

There is no need to use the verbose std::initializer_list inside the loop

#include <iostream>
#include <initializer_list>

struct B { virtual int fun() { return 0; } };
struct D1 : B { int fun() { return 1; } };
struct D2 : B { int fun() { return 2; } };

int main()
{
    D1 x;
    D2 y;

    B* px = &x;
    B* py = &y;

    for (auto& e : { px, py })
            std::cout << e->fun() << "\n";    
}

Live Example.

If you want to do it on-the-fly without defining px and py, you can indeed use std::initializer_list<B*>{ &x, &y } inside the loop.

like image 85
TemplateRex Avatar answered Oct 10 '22 08:10

TemplateRex