==== 動的メモリの取得と可変配列(vector) ==== * 静的配列 * これまで使ってきたコンパイル時に数が決まっていないとダメな配列 * const int NUM = 10; int arr[NUM]; みたいなやつ * 動的配列 * 必要な時に必要な数だけ用意する配列 * メモリの取得と、メモリのアドレスの先頭部分を記憶する変数(ポインタ変数)が必要 * int *pArr; pArr = new int[100]; こんな感じで使う * いらなくなったら delete[] pArr; で後片付けが必要 * ポインタ変数は int *pArr = nullptr; (nullptrは何も指さない初期化用のアドレス)で初期化する * 可変配列 * 途中で自由に長さを変更できる配列、 C++ではstd::vectorが有名 * 以下プログラムを参照 動的メモリの配列と可変配列 #include #include using std::cout; using std::cin; using std::endl; //using namespace std; const int MAX_ARR_NUM = 10; void getArray() { int num; //動的配列のためのメモリアドレスの用意(ポインタ変数) int* pArr = nullptr; //配列メモリアドレスを用意 //nullptrは初期化用なにも指していないメモリアドレスを表している cout << "数を入力:"; cin >> num; //動的配列の取得 new pArr = new int[num]; //用意したメモリアドレスにint num個分の配列を展開 for (int i = 0; i < num; i++) pArr[i] = i + 1; for (int i = 0; i < num; i++) cout << pArr[i] << " "; if(pArr!=nullptr) delete[] pArr; } int main() { //静的配列 int arr[MAX_ARR_NUM]={ 1,2,3,4,5,4,3,2,1,0 }; std::vector vInt; cout << "length:" << vInt.size() << endl; vInt.push_back(1); cout << "length:" << vInt.size() << endl; vInt.push_back(2); cout << "length:" << vInt.size() << endl; vInt.push_back(3); cout << "length:" << vInt.size() << endl; vInt.push_back(4); cout << "length:" << vInt.size() << endl; for (int i = 0; i < vInt.size(); i++) cout << vInt[i] << " "; for (auto e : vInt) cout << e << " "; return 0; } == 参考 == [[https://www.yz-learning.com/yzwiki/doku.php?id=game-engineer:classes:2022:game-programing-1:second-term:11:11-02-2|動的オブジェクトの取得]]\\ [[https://www.yz-learning.com/yzwiki/doku.php?id=game-engineer:classes:2022:game-programing-1:second-term:12:12-22-2&s[]=vector|vectorとかarrayとか]]\\