创建具有非常量大小的 int 数组
Creating an int array with a non-const size
我目前正在为游戏制作插件,但遇到了以下问题:
我想让用户选择半径,但由于 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++ 不允许我创建大小可变的数组,所以我无法获得自定义半径。
这个很好用
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());