どうも、ちょげ(@chogetarou)です。
erase()
でVectorの末尾からN個の要素を削除する方法を紹介します。
方法

erase()
でVectorの後ろからN個の要素を削除するには、end()を使います。
まず、Vectorからerase()を呼び出します。
そして、erase()の第1引数にVectorのend()を削除する要素数で引いた値、第2引数にVectorのend()を指定します。
//vect=任意のVector, n=削除する要素数
vect.erase(vect.end() - n, vect.end());
上記のerase()は、Vectorの末尾からN個の要素を削除します。
使用例
#include <iostream>
#include <vector>
using namespace std;
int main(void){
vector<int> num = { 1, 2, 3, 4, 5, 6 };
int n = 3;
num.erase(num.end() - n, num.end());
for (int &i: num) {
cout << i << endl;
}
}
出力:
1
2
3
コメント