std::vector::insert
插入元素
通过在指定位置的元素之前插入新元素来扩展,从而通过插入的元素数量有效地增加容器大小。
iterator insert (iterator pos, const T& val);
pos:在插入新元素的pos的位置。迭代器是一种成员类型,定义为指向元素的随机访问迭代器类型。
val: 数据
返回值:指向第一个新插入元素的迭代器。成员类型迭代器是指向元素的随机访问迭代器类型。
复杂性 : 插入的元素数量(复制/移动构造)加上定位(移动)后的元素数量呈线性关系。
//insert 模拟实现
iterator insert(iterator pos, const T& x)
{
assert(pos >= _start && pos <= _finish);
if (_finish == _endOfStorage) //_finish :最后一个数据后的指针 endofstorage 开辟的空间结尾的指针
{
reserve(capacity() == 0 ? 4 : capacity() * 2);
}
iterator end = _finish - 1;
while (end >= pos)
{
*(end + 1) = *end;
--end;
}
*pos = x;
++_finish;
return pos;
}
void VectorSimulationImplementatio1()
{
st::vector<int> v;
v.push_back(1);//尾插数据
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
for (auto e : v)
{
cout << e << "";
}
cout << endl;
v.insert(v.begin() + 1, 11);
v.insert(v.begin() + 1, 10);
for (auto e : v)
{
cout << e << "";
}
cout << endl;
}
int main()
{
st::VectorSimulationImplementatio1();
return 0;
}
正常插入数据;
此时v.capacity=8,v.size=5;插入11与10,v.size = 7 < v.capacity;
void VectorSimulationImplementatio1()
{
st::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
v.push_back(6);
v.push_back(7);
v.push_back(8);
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
v.insert(v.begin() + 1, 11);
v.insert(v.begin() + 1, 10);
for (auto e : v)
{
cout << e << "";
}
cout << endl;
}
第一个调用成功插入
当容量使用完后,调用insert(),空间不足会进行扩容:
if (_finish == _endOfStorage) { reserve(capacity() == 0 ? 4 : capacity() * 2); }
![在这里插入图片描述](https://img-blog.csdnimg.cn/002c2a5daf164e5c925c5d8734649854.png
扩容后 capacity: 8 → 16;
(当扩容不是原地扩容,而是异地扩容时,迭代器将会失效)
异地扩容后,迭代器指针还在原来的空间,所以失效了;
解决方法,记录一下迭代器的位置
iterator insert(iterator pos, const T& x)
{
assert(pos >= _start && pos <= _finish);
if (_finish == _endOfStorage)
{
size_t len = pos - _start; //记录pos的位置
reserve(capacity() == 0 ? 4 : capacity() * 2);
pos = len + _start;//更新pos
}
iterator end = _finish-1;
while (end >= pos)
{
*(end + 1) = *end;
--end;
}
*pos = x;
++_finish;
return pos;
}
迭代器有效性:如果发生重新分配,则与容器相关的所有迭代器、指针和引用都将失效。否则,只有那些指向位置和超越的元素是无效的,所有迭代器、指针和对位置之前元素的引用保证继续引用它们在调用之前引用的相同元素。