erase函数
语法:
1 2 |
iterator erase(iterator __position); iterator erase(iterator __first, iterator __last); |
erase() 删除指定元素
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
/** * @brief Remove element at given position. * @param position Iterator pointing to element to be erased. * @return An iterator pointing to the next element (or end()). * * This function will erase the element at the given position and thus * shorten the %vector by one. * * Note This operation could be expensive and if it is * frequently used the user should consider using std::list. * The user is also cautioned that this function only erases * the element, and that if the element is itself a pointer, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibilty. */ iterator erase(iterator __position); /** * @brief Remove a range of elements. * @param first Iterator pointing to the first element to be erased. * @param last Iterator pointing to one past the last element to be * erased. * @return An iterator pointing to the element pointed to by @a last * prior to erasing (or end()). * * This function will erase the elements in the range [first,last) and * shorten the %vector accordingly. * * Note This operation could be expensive and if it is * frequently used the user should consider using std::list. * The user is also cautioned that this function only erases * the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibilty. */ iterator erase(iterator __first, iterator __last); |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1; vector<int> v2(10, 2); v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); vector<int>::iterator iter = v1.begin(); v1.erase(iter); for(int i=0;i<v1.size();i++) cout<<v1[i]<<","; cout<<endl; iter = v1.begin(); vector<int>::iterator iterend = v1.end(); v1.erase(iter, iterend); cout<<"v1向量内元素数:"<<v1.size()<<endl; } |
测试结果:
1 2 |
2,3,4,5, v1向量内元素数:0 |