Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a constant sized array in an initializer list

I've got a situation which can be summarized in the following:

class Test {      Test();      int MySet[10];  }; 

is it possible to initialize MySet in an initializer list?

Like this kind of initializer list:

Test::Test() : MySet({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) {} 

Is there any way to initialize a constant-sized member array in a class's initalizer list?

like image 728
Serge Avatar asked Aug 06 '12 22:08

Serge


People also ask

How do you initialize an entire array with any value in CPP?

int arr[10] = {5}; In the above example, only the first element will be initialized to 5. All others are initialized to 0. A for loop can be used to initialize an array with one default value that is not zero.

How do you declare a constant array size in C++?

const int size = 2; int array[size] = {0}; Here, 2 is a literal value, that means, you can't change it, and the compiler know the value at compile-time. int a = 2; int size = a; int* array = new int[size]; thus, you can apply for an array with dynamic size.

Can you initialize array with variable size?

But, unlike the normal arrays, variable sized arrays cannot be initialized.


2 Answers

While not available in C++03, C++11 introduces extended initializer lists. You can indeed do it if using a compiler compliant with the C++11 standard.

struct Test {     Test() : set { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } { };     int set[10]; }; 

The above code compiles fine using g++ -std=c++0x -c test.cc.


As pointed out below me by a helpful user in the comments, this code does not compile using Microsoft's VC++ compiler, cl. Perhaps someone can tell me if the equivalent using std::array will?

#include <array>  struct Test {   Test() : set { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } } { };   std::array<int, 10> set; }; 

This also compiles fine using g++ -std=c++0x -c test.cc.

like image 90
obataku Avatar answered Sep 19 '22 21:09

obataku


Unfortunately, in C++03, you cannot initialize arrays in initializer lists. You can in C++11 though if your compiler is newer :)

see: How do I initialize a member array with an initializer_list?

like image 36
John Humphreys Avatar answered Sep 20 '22 21:09

John Humphreys