创建大小为非const的整型数组
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());
相关文章:
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- 如何将SHA1转换为无符号长整型数组[5]
- 我需要以相反的方式复制一个长整型数组,我需要系统函数,例如 memcpy 有没有
- 复制存储在空指针的整型数组到整型数组
- 如何使用SSE来处理整型数组,使用条件
- 序列化/反序列化整型数组为char数组
- c++将整型数组赋值给大小相同的空整型数组
- 按值传递时改变整型数组的大小
- c++排序(升序,降序)整型数组
- 将字符串转换为整型数组
- 将二进制文件读入整型数组
- 在整型数组的最后一个元素中存储数据的问题
- 读取文件并将其作为整型数组输入
- 稍后在{}中添加无符号整型数组
- 用户输入存储在整型数组中的值c++
- 当使用整型数组的一部分时
- 将整型数组传递给c++ DLL
- 将字符数组转换为整型数组
- 引用整型数组的指针
- 比较浮点数组和整型数组