Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert C array to std::initializer_list?

I know a pointer to an array and its size. What container can be created from it? I tried to do this:

std::initializer_list<int> foo(arr, arr + size);

It works for the MSVC, but not for the gcc

like image 286
Игорь Пугачев Avatar asked Mar 19 '26 14:03

Игорь Пугачев


1 Answers

std::initializer_list is a reference-type designed just for supporting list-initialization, and only has the default-ctor, and implicitly copy-ctor. Any other ctor is an extension.

What you can do is initializing the target-container directly from an iterator-range, without involving any intermediate views.

The standard container to use unless you know better would be std::vector. Or would using a simple view like std::span be enough for you?

like image 161
Deduplicator Avatar answered Mar 22 '26 06:03

Deduplicator