创建一个大小不是常量的整数数组

3

我目前正在为一款游戏制作插件,遇到以下问题:

我想让用户选择半径,但由于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];

?


3
你考虑过使用 std::vector 吗? - R Sahu
我认为这不会起作用,GET_PED_NEARBY_VEHICLES函数的定义如下:图片 - Hx0
1
@Hx0 std::vectordata()成员函数,专门用于此。 - emlai
1个回答

4

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());

搞定了,谢谢!我不知道向量可以解决这个问题(以前几乎从未使用过它们,对c++相当新)。 - Hx0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接