创建大小为非const的整型数组

Creating an int array with a non-const size

本文关键字:整型 数组 const 小为 创建      更新时间:2023-10-16

我目前正在制作一个游戏插件,我有以下问题:

我想让用户选择半径,但由于c++不允许我创建可变大小的数组,所以我无法获得自定义半径。

        const int numElements = 25;
    const int arrSize = numElements * 2 + 2;
    int vehs[arrSize];
    //0 index is the size of the array
    vehs[0] = numElements;
    int count = GET_PED_NEARBY_VEHICLES(PLAYER_PED_ID(), vehs);

但这不是:

    int radius = someOtherVariableForRadius * 2;
    const int numElements = radius;
    const int arrSize = numElements * 2 + 2;
    int vehs[arrSize];
    //0 index is the size of the array
    vehs[0] = numElements;
    int count = GET_PED_NEARBY_VEHICLES(PLAYER_PED_ID(), vehs);
是否有可能修改const int而不会在 中产生错误?
int vehs[arrSize];

?

数组的大小必须是c++中的编译时常量。

在您的第一个版本中,arrSize是编译时常数,因为它的值可以在编译时计算。

在第二个版本中,arrSize不是编译时常数,因为它的值只能在运行时计算(因为它取决于用户输入)。

解决这个问题的惯用方法是使用std::vector:
std::vector<int> vehs(arrSize);
//0 index is the size of the array
vehs[0] = numElements;

要获得指向底层数组的指针,请调用data():

int count = GET_PED_NEARBY_VEHICLES(PLAYER_PED_ID(), vehs.data());