简体   繁体   English

在C ++中初始化大小固定的数组

[英]Initialize an array in C++ whose size is not fixed

I have a C++ application where I want to use an array that is initialized on its declaration. 我有一个C ++应用程序,我想使用在其声明中初始化的数组。 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. 开发时可能发生的一种情况是,通过增加或减少项目数量来更改MyEnum定义。 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? 还是在这种特定情况下,我总是必须在更改MyEnum时手动更改其初始化?

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. 使用for循环或任何此类方法的任何答复都不是有效的答复,因为我在谈论的是在其声明上而不是代码中进一步初始化数组。
  • Although my initial code took my array as being a static one, the question is actually universal, that is, independent on the array being static or not. 尽管我的初始代码将数组视为static数组,但问题实际上是通用的,也就是说,与数组是否static无关。 So no reply that takes advantage of a array being static is valid. 因此,没有利用数组为static回复是有效的。 Of course that not being a static 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". 当然,不是static数组会引发一个问题,即为什么不使用for循环或类似于初始化,但是在这种情况下,答案应该仅是“切换情况”:“如果您有这样的数组,这样做的方法是休闲的;如果您有另一种数组,那么方法是另一种”。
  • 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. 该代码示例附带一个仅带有“ false”的布尔数组,但是这种情况实际上是通用的,也就是说,该数组可能只填充了“ true”,或者甚至是通过某种算法排序的“ true”和“ false”的组合甚至可能不是布尔数组,而是int或char或其他类型。
  • I'm talking about arrays, not vectors or any C++ container ;) 我说的是数组,而不是向量或任何C ++容器;)

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! 谢谢!

It is simple to do by specifying an empty brace-init list 指定空的括号初始化列表很容易

void myMethod()
{    
    static bool myArray[MyEnumCount] = {};
    //...
}

In this case all elements of the array will be initialized to false . 在这种情况下,数组的所有元素都将初始化为false As the array is static then you may even do not specify the initializer. 由于数组是静态的,因此您甚至可以不指定初始化程序。 It will be zero-initialized by the compiler itself. 它将由编译器本身初始化为零。

Take into account that you could use std::array : 考虑到您可以使用std::array

For example 例如

void myMethod()
{    
    static array<bool, MyEnumCount> myArray = {};
    //...
}

In this case you could reassign the array using the brace-init list. 在这种情况下,您可以使用brace-init列表重新分配阵列。

The code you have there (with MyEnumCount ) will work since the MyEnumCount is constant at compile time. 您那里的代码(带有MyEnumCount )将可以正常工作,因为MyEnumCount在编译时是恒定的。

With respect to the initialisation, there are some options available to you; 关于初始化,您可以使用一些选项。

static bool myArray[MyEnumCount] = {};

Or (if the value is something more complex 或者(如果值更复杂

static bool myArray[MyEnumCount];
// some place safe...
for (auto it = std::begin(myArray); it != std::end(myArray), ++it) {
  *it = false;
}

If you want to initialize everything to false, use an empty list: 如果要将所有内容初始化为false,请使用一个空列表:

bool myArray[MyEnumCount] = {};

If you want to initialize everything to something else, use std::fill or std::fill_n : 如果要将所有内容初始化为其他内容,请使用std::fillstd::fill_n

bool myArray[MyEnumCount];
std::fill_n(myArray, MyEnumCount, true);
// or std::fill(myArray, myArray + MyEnumCount, true);

If it wasn't static, 如果不是静态的

bool myArray[MyEnumCount];
for (int i=MyEnumCount; i--; )
   myArray[i] = false;

It's fine to use an initializer that doesn't specify enough values, and the remaining values will take the default for that type: 可以使用未指定足够多的值的初始化程序,其余值将采用该类型的默认值:

enum MyEnum
{
    Item1,
    Item2,
    Item3,

    MyEnumCount
};

//In .cpp
void myMethod()
{    
    bool myArray[MyEnumCount] = {false, true};  // The third will be false
    //...
}

Do you have to use arrays? 您必须使用数组吗? or can you use standard containers? 还是可以使用标准容器? For example, with vectors this can be easily done: 例如,使用向量可以很容易地做到这一点:

static std::vector<bool> myArray(false, MyEnumCount);

but there might be some problems with this being a static array. 但是将其作为静态数组可能会出现一些问题。 You need to make sure when the array is being initialized that the variable MyEnumCount has been already defined. 您需要确保在初始化数组时已定义变量MyEnumCount In your case, because the static array is inside a function, you just need to make sure it is called after the definition of the count, which probably is. 在您的情况下,由于静态数组位于函数内部,因此您只需要确保在定义计数(可能是计数)之后调用它即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM