導入
vector には末尾以外への操作や、要素の削除、先頭・末尾の参照など、実務で使うメソッドがそろっています。さらに vector を入れ子にすると「表」も表せます。
説明
代表的な操作を整理します。
flowchart LR v["vector v"] --> a[".push_back(x)<br/>末尾に追加"] v --> b[".pop_back()<br/>末尾を削除"] v --> c[".front() / .back()<br/>先頭・末尾の値"] v --> d[".insert / .erase<br/>途中に挿入・削除"] v --> e[".clear() / .empty()<br/>全消し・空判定"]
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {10, 20, 30};
v.pop_back(); // 末尾を削除 → {10, 20}
cout << v.front() << " " << v.back() << endl; // 10 20
v.insert(v.begin() + 1, 15); // 1番目の位置に挿入 → {10, 15, 20}
v.erase(v.begin()); // 先頭を削除 → {15, 20}
for (int x : v) cout << x << " "; // 15 20
cout << endl;
cout << v.empty() << endl; // 0(空でない)
return 0;
}
vector の中に vector を入れると、2次元(表・グリッド)を表せます。第5章の多次元配列より柔軟です。
#include <iostream>
#include <vector>
using namespace std;
int main() {
// 2行3列を 0 で初期化
vector<vector<int>> grid(2, vector<int>(3, 0));
grid[0][1] = 5;
grid[1][2] = 9;
for (int y = 0; y < (int)grid.size(); y++) {
for (int x = 0; x < (int)grid[y].size(); x++) {
cout << grid[y][x] << " ";
}
cout << endl;
}
// 0 5 0
// 0 0 9
return 0;
}
まとめ
insert / erase は位置を「イテレータ」(v.begin() からの相対)で指定します。2次元データは vector<vector<T>> で表せて、行ごとに長さを変えることもできます。