Why use initializer_list instead of vector in parameters?

后端 未结 3 2059

What is the actual benefit and purpose of initializer_list, for unknown number of parameters? Why not just use vector and be done with it?

In f

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 21:33

    The biggest advantage of initializer_list over vector is that it allows you to specify in-place a certain sequence of elements without requiring dedicate processing to create that list.

    This saves you from setting up several calls to push_back (or a for cycle) for initializing a vector even though you know exactly which elements are going to be pushed into the vector.

    In fact, vector itself has a constructor accepting an initializer_list for more convenient initialization. I would say the two containers are complementary.

    // v is constructed by passing an initializer_list in input
    std::vector v = {"hello", "cruel", "world"};
    

    Of course it is important to be aware of the fact that initializer_list does have some limitations (narrowing conversions are not allowed) which may make it inappropriate or impossible to use in some cases.

提交回复
热议问题