1

I want to declare a large array with every value set to DEFAULT_VALUE in initialization except three values at places throughout the array.

Writing int array[2048] = { DEFAULT_VALUE };

will fill the whole array with the default, and

int array[2048] = { [4] = VALUE_1, [123] = VALUE_2, [2047] = VALUE_3 };

will set specific indexes and the rest to zero (it is in global space), but how can I initialize the array to have specific values AND my own default value? Can I write my own initialization routine?

Speed is a priority here btw.

2
  • In case you didn't know, the second is a compiler-specific extension and not standard C++. Commented Mar 9, 2020 at 15:37
  • "Writing int array[2048] = { DEFAULT_VALUE }; will fill the whole array with the default" - no, it won't. It will fill in only the 1st element with DEFAULT_VALUE, the rest of the elements will be value-initialized to 0 instead. Commented Mar 9, 2020 at 18:30

4 Answers 4

1

If you don't mind a dynamic memory allocation, I would just use a std::vector like

std::vector<int> array(2048, DEFAULT_VALUE); array[4] = VALUE_1; array[123] = VALUE_2; array[2047] = VALUE_3; 

Which optimizes quite well in this live example

Sign up to request clarification or add additional context in comments.

Comments

0

As with so many optimization questions, profile your code before optimizing. I highly doubt that initializing this array could be a bottleneck in any scenario.

That being said, there is no clean syntax for this. Just set the values from a reasonable initialization routine yourself. This is what the compiler would do anyway.

Consider also using std::array or std::vector.

Comments

0

I ended up solving my problem by mixing c and c++ in my program. I used "extern C" where appropriate. Using C I can write:

int array[256] = { [0 ... 255] = DEFAULT_VALUE, [4] = VALUE_1 }; 

to set the whole array to my own default value except where specified otherwise. I like clean code so switching to C for this one feature worked for me. Vectors and the heap are not options, as this code will run on an embedded system.

Comments

0

You can use std::valarray:

std::valarray<int> v(DEFAULT_VALUE, 2048); v[std::_Sizarray{ 4, 123, 2034 }] = { VALUE_1, VALUE_2, VALUE_3 }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.