vector成员函数pop_back()删掉最后一个元素,而函数erase()可以用来删掉有一个iterator指出的元素,也可以删掉一个范围的元素,代码如下:
#include <vector>
#include <iostream>
using namespace std;
void main (void) {
vector<int> vector1; // define a vector of integers
for (int i = 0; i < 10; ++i)
vector1.push_back(i);
cout << "vector contains " << vector1.size() << " elements" << endl;
vector1.pop_back(); // erase the last element 9
cout << "vector contains " << vector1.size() << " elements" << endl;
vector1.erase(vector1.begin()); // erase the first element (1) using an iterator
cout << "vector contains " << vector1.size() << " elements" << endl;
vector1.erase(vector1.begin(), vector1.end()); // erase all the remaining elements
cout << "vector contains " << vector1.size() << " elements" << endl;
}
另外,如果为list容器,因为内存不是连续的,则只能重载++或者--,所以要指定删除某一个元素的时候不能vector::iterator p=vector::begin()+1什么的!