发布时间:2025-06-24 19:36:50 作者:北方职教升学中心 阅读量:518
- 迭代器失效的解决办法:在使用前,对迭代器重新赋值。
2.指定位置元素的删除操作erase().
erase删除pos位置元素后,pos位置之后的元素会往前移,没有导致底层空间的改变,理论上来讲迭代器是不会失效的。
vector的代码展示
#pragma once#include<iostream>#include<assert.h>namespace my_vector{ template<class T> class vector { public: typedef T* iterator; typedef const T* const_iterator; iterator begin() { return _start; } iterator end() { return _finish; } const_iterator begin() const { return _start; } const_iterator end() const { return _finish; } vector() :_start(nullptr) , _finish(nullptr) , _end_of_storage(nullptr) {} ~vector() { if (_start) { delete[] _start; _start = _finish = _end_of_storage = nullptr; } } size_t size() const { return _finish - _start; } size_t capacity() const { return _end_of_storage - _start; } void push_back(const T& x) { if (_finish == _end_of_storage) { size_t newcapacity = (capacity() == 0 ? 4 : capacity() * 2); reserve(newcapacity); } *_finish = x; ++_finish; } iterator insert(iterator pos, const T& x) { assert(pos >= _start && pos <= _finish); if (_finish == _end_of_storage) { size_t len = pos - _start; size_t newcapacity = (capacity() == 0 ? 4 : capacity() * 2); reserve(newcapacity); pos = _start + len; } iterator end = _finish - 1; while (end >= pos) { *(end + 1) = *end; end--; } *pos = x; ++_finish; return pos; } void reserve(size_t n) { if (capacity() < n) { size_t sz = size(); T* tmp = new T[n]; if (_start) { //memcpy(tmp, _start, sizeof(T) * sz); for (size_t i = 0; i < sz; ++i) { tmp[i] = _start[i]; } delete[] _start; } _start = tmp; _finish = _start + sz; _end_of_storage = _start + n; } } T& operator[](size_t pos) { assert(pos < size()); return _start[pos]; } const T& operator[](size_t pos) const { assert(pos < size()); return _start[pos]; } iterator erase(iterator pos) { assert(pos >= _start && pos < _finish); iterator it = pos + 1; while(it != _finish) { *(it - 1) = *it; it++; } _finish--; return pos; } void pop_back() { erase(_finish - 1); } void resize(size_t n, const T& val = T()) { if (n < size()) { _finish = _start + n; } else { reserve(n); while (_finish != _start + n) { *_finish = val; ++_finish; } } } vector(const vector<T>& v) { _start = new T[v.capacity()]; for (size_t i = 0; i < v.size(); ++i) { _start[i] = v._start[i]; } _finish = _start + v.size(); _end_of_storage = _start + v.capacity(); } void swap(vector<T>& v) { std::swap(_start, v._start); std::swap(_finish, v._finish); std::swap(_end_of_storage, v._end_of_storage); } vector<T>& operator=(vector<T> v) { swap(v); return *this; } private: iterator _start; iterator _finish; iterator _end_of_storage; };}