C ++ indicates array indices in an initializer, e.g. C

I used C before (inline material) and I can initialize my arrays as follows:

int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 }; 

i.e. I can specify indexes inside the initializer. I am currently learning Qt/C++ , and I cannot believe that this is not supported in C ++.

I have this option: -std=gnu++0x , but in any case it is not supported. (I don't know if this is supported in C ++ 11 because Qt is working with an error with gcc 4.7.x)

So, is this not really supported in C ++? Or maybe there is a way to turn it on?

UPD: Currently, I want to initialize a const array, so std::fill will not work.

+8
c ++ c
source share
3 answers

Over the years, I tested this by accident, and I can confirm that it works in g++ -std=c++11 , g ++ version 4.8.2.

+1
source share

hm, you should use std :: fill_n () for this task ...

as stated here http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html the assigned inits (extention) are not implemented in GNU C ++

edit: taken from here: initialize const array in class initializer in C ++

as the comment said, you can use std: vector to get the desired result. You can still force const to be used differently and use fill_n.

 int* a = new int[N]; // fill a class C { const std::vector<int> v; public: C():v(a, a+N) {} }; 
+7
source share

No, this cannot be done in C ++. But you can use the std :: fill algorithm to assign values:

 int widths[101]; fill(widths, widths+10, 1); fill(widths+10, widths+100, 2); fill(widths+100, widths+101, 3); 

It is not so elegant, but it works.

+2
source share

All Articles