初始化器列表在一个范围for循环 [英] Initializer list in a range for loop
问题描述
我有一个不同类型的对象从一个超类型派生。我不知道如果使用 std :: initializer
列表在一个范围内的循环像这样有什么缺点:
for(auto object:std :: initializer_list< Object *> {object1,object2,object3}){
pre>
}
它是完全正确和有效的,还是最好使用数组?对我来说,
std :: array
解决方案似乎对编译器更加限制,并且有明确说明大小的缺点:for(auto object:std :: array< Object *,3> {object1,object2,object3}){
}
有没有其他或更好的方法迭代显式给定的对象列表?
解决方案在循环中不需要使用详细的
std :: initializer_list
#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()< \\\
;
}
活动示例 。
fly不定义
px
和py
,你可以使用std :: initializer_list< B * > {& x,& y}
。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?
解决方案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"; }
If you want to do it on-the-fly without defining
px
andpy
, you can indeed usestd::initializer_list<B*>{ &x, &y }
inside the loop.这篇关于初始化器列表在一个范围for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!