Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ specify array indexes in initializer, like C

Tags:

c++

c

I used C before (embedded stuff), and I can initialize my arrays like that:

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

i.e. I can specify indexes inside initializer. Currently I'm learning Qt/C++, and I can't believe this isn't supported in C++.

I have this option: -std=gnu++0x, but anyway it isn't supported. (I don't know if it is supported in C++11, because Qt works buggy with gcc 4.7.x)

So, is it really not supported in C++? Or maybe there's a way to enable it?

UPD: currently I want to initialize const array, so std::fill won't work.

like image 355
Dmitry Frank Avatar asked Nov 26 '12 10:11

Dmitry Frank


People also ask

What is the right way to initializer array in C?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

Does C initialize arrays to 0?

Initialize Arrays in C/C++ c. The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.


3 Answers

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

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

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

as a comment said, you can use std:vector to get the result desired. You could still enforce the const another way around and use fill_n.

int* a = new int[N];
// fill a

class C {
  const std::vector<int> v;
public:
  C():v(a, a+N) {}
};
like image 103
Najzero Avatar answered Oct 23 '22 05:10

Najzero


After years, I tested it just by chance, and I can confirm that it works in g++ -std=c++11, g++ version is 4.8.2.

like image 38
Dmitry Frank Avatar answered Oct 23 '22 05:10

Dmitry Frank


No, it is not possible to do it in C++ like that. But you can use std::fill algorithm to assign the values:

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

It is not as elegant, but it works.

like image 2
Juraj Blaho Avatar answered Oct 23 '22 03:10

Juraj Blaho