先看以下代码:

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 int main(void)
 5 {
 6     vector<int>array = {100, 300, 300, 300, 300, 500};

13 for (size_t i = 0; i < array.size(); ++i) 14 { 15 cout << &array[i] << " -> " << array[i] << endl; 16 } 17 vector<int>::iterator itor; 18 for (itor = array.begin(); itor != array.end(); itor++) 19 { 20 if (*itor == 300) 21 { 22 itor = array.erase(itor); 23 } 24 } 25 for (size_t i = 0; i < array.size(); ++i) 26 { 27 cout << &array[i] << " -> " << array[i] << endl; 28 } 29 for (itor = array.begin(); itor != array.end(); itor++) 30 { 31 cout << *itor << ""; 32 } 33 return 0; 34 }

结果竟然如下:

我们将其删除前后每个元素的地址打印出来,如下:

erase在删除当前元素后,会将其后元素前移,以保证vector的连续存储。

vs编译器erase实现:

 1 iterator erase(const_iterator _Where)
 2 {    // erase element at where
 3     if (_VICONT(_Where) != this
 4         || _VIPTR(_Where) < this->_Myfirst
 5         || this->_Mylast <= _VIPTR(_Where))
 6         _DEBUG_ERROR("vector erase iterator outside range");
 7     _Move(_VIPTR(_Where) + 1, this->_Mylast, _VIPTR(_Where)); //移动
 8     _Destroy(this->_Mylast - 1, this->_Mylast);
 9     _Orphan_range(_VIPTR(_Where), this->_Mylast);
10     --this->_Mylast;
11     return (_Make_iter(_Where));
12 }

`stl_vector.h`实现:

1 iterator erase(iterator position) {
2     if (position + 1 != end())
3         copy(position + 1, finish, position); //copy至前面
4     --finish;
5     destroy(finish);
6     return position;
7 }

上面程序,在每次erase后,erase返回的迭代器就已经指向被删除元素后一个元素,再++,就会跳过一个元素(300)。

版权声明:本文为dabai56原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/dabai56/p/10955482.html