gpt4 book ai didi

c++ - 创建具有非常量大小的 int 数组

转载 作者:行者123 更新时间:2023-11-30 03:51:05 25 4
gpt4 key购买 nike

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

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

关于c++ - 创建具有非常量大小的 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31487836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com