I have a C++ application where I want to use an array that is initialized on its declaration. The problem, though, is that the number of items is not fixed in the "normal" way, but it's based on a "counter" number inside a enum:
//"Normal way"
void myMethod()
{
bool myArray[3] = { false, false, false };
//...
}
//My way
//In .hpp
enum MyEnum
{
Item1,
Item2,
...,
MyEnumCount
}
//In .cpp
void myMethod()
{
bool myArray[MyEnumCount] = { false, false, false };
//...
}
One situation that might occur while developing is a change in the MyEnum
definition, either by increasing or decreasing the number of items on it. The idea is that, in case this happens, the code would automatically adapt itself to the new enum, without having to manually go to parts of the code for specific editions. Is there a way to do this in that array initialization? Or in this specific case, I would have to manually change its initialization always when MyEnum is changed?
Edit: Thanks for the all the replies written so far. I'm editing my question because I think my example above mislead some users in providing an answer for the actual question that was made (which is, actually, slightly different from the code I want for my app).
Restating my question: how does one initialize an array on its declaration with the values he wants when the size of the array is determined by a enum value which may be edited during code development without having to re-write the initialization?
This means:
- No reply that uses a for-loop or any such a method is a valid one, since I'm talking about initializing the array on its declaration, not further in the code.
- Although my initial code took my array as being a
static
one, the question is actually universal, that is, independent on the array beingstatic
or not. So no reply that takes advantage of a array beingstatic
is valid. Of course that not being astatic
array would left opened the question about why not use a for loop or similar to to the initialization, but in that case the answer should only do a "switch case": "if you have such an array, the way of doing this is the fallowing; if you have another kind of array, then the way is this other". - The code example came with a bool array with only "false", but the situation is actually universal, that is, the array may be filled with only "true" or even a combination of "true" and "false" sorted by some algorithm or even may not be a boolean array after all, but a int or a char or whatever.
- I'm talking about arrays, not vectors or any C++ container ;)
Since I made this edits, I'll wait till tomorrow for a complete answer and, if not, I'll made one with the answers you provided. Thanks!