[英]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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.