Vector的底层数据结构
元素增加
push_back
void push_back(const _Tp& __x) {
if (_M_finish != _M_end_of_storage) {
construct(_M_finish, __x);
++_M_finish;
} else {
_M_insert_aux(end(), __x);
}
}
insert (iterator __pos, size_type __n, const _Tp& __x)
void insert (iterator __pos, size_type __n, const _Tp& __x) {
_M_fill_insert(__pos, __n, __x);
}
元素删除
iterator erase(iterator __first, iterator __last) {
iterator __i = copy(__last, _M_finish, __first);//copy the elements at range of [__last, _M_finish) to the position __first
destroy(__i, _M_finish);// call the destructor of the releaded elements 不会释放内存
_M_finish = _M_finish - (__last - __first);//adjust the posirion index
return __first;
}
notes
at()与 operator[] 下标操作符的区别:
at 操作首先会检查下标是否越界,越界则抛出异常。