其他分享
首页 > 其他分享> > 剖析vector.erase()实现

剖析vector.erase()实现

作者:互联网

先看以下代码:

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 int main(void)
 5 {
 6     vector<int>array;
 7     array.push_back(100);
 8     array.push_back(300);
 9     array.push_back(300);
10     array.push_back(300);
11     array.push_back(300);
12     array.push_back(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后,迭代器依然指向原始位置,但现在该位置存放的是删除前被删除元素的后一个元素,再++,就会跳过一个元素(300)。

标签:itor,300,back,剖析,vector,erase,array,Where
来源: https://www.cnblogs.com/dabai56/p/10955482.html