1. 什么是vector
vector是一个空间可以动态增长的数组。
2. 模拟实现
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <assert.h>
using namespace std;
namespace lzh {
template<typename T>
class vector {
public:
// Vector的迭代器是一个原生指针
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;
}
// construct and destroy
//初始化列表给指针置空或者给缺省值
vector() {
}
vector(int n, const T& val = T()) {
resize(n, val);
}
template<class InputIterator>
vector(InputIterator first, InputIterator last) {
while (first != last) {
push_back(*first);
++first;
}
}
/*vector(const vector<T>& v) {
_start = new T[v.size()];
for (size_t i = 0; i < v.size(); ++i) {
_start[i] = v._start[i];
}
_finish = _start + v.size();
_endOfStorage = _start + v.capacity();
}*/
vector(const vector<T>& v) {
reserve(v.size());
for (auto& i : v) {
push_back(i);
}
}
void swap(vector<T>& v) {
std::swap(_start, v._start);
std::swap(_finish, v._finish);
std::swap(_endOfStorage, v._endOfStorage);
}
vector<T>& operator= (vector<T> v) {
swap(v);
return *this;
}
~vector() {
if (_start) {
delete[] _start;
_start = _finish = _endOfStorage = nullptr;
}
}
// capacity
size_t size() const {
return _finish - _start;
}
size_t capacity() const {
return _endOfStorage - _start;
}
void reserve(size_t n) {
if (n > capacity()) {
T* temp = new T[n];
size_t oldSize = size();
if (_start) {
for (size_t i = 0; i < oldSize; ++i) {
temp[i] = _start[i];
}
delete[] _start;
}
_start = temp;
_finish = temp + oldSize;
_endOfStorage = temp + n;
}
}
void resize(size_t n, const T& val = T()) {
size_t _size = size();
if (n > _size && n - _size > (size_t)(_endOfStorage - _finish)) {
reserve(n);
}
while (_size < n) {
push_back(val);
++_size;
}
_finish = _start + n;
}
///access///
T& operator[](size_t pos) {
assert(_start + pos < _finish);
return _start[pos];
}
const T& operator[](size_t pos)const {
assert(_start + pos < _finish);
return _start[pos];
}
///modify/
void push_back(const T& x) {
/*if (_finish == _endOfStorage) {
size_t _capacity = capacity();
reserve(_capacity ? _capacity * 2 : 1);
}
_finish[0] = x;
++_finish;*/
insert(end(), x);
}
void pop_back() {
assert(_finish);
--_finish;
}
iterator insert(iterator pos, const T& x) {
assert(pos >= _start && pos <= _finish);
//迭代器失效
if (_finish == _endOfStorage) {
size_t len = pos - _start;
size_t _capacity = capacity();
reserve(_capacity ? _capacity * 2 : 1);
pos = _start + len;
}
iterator end = _finish;
while (end > pos) {
end[0] = end[-1];
--end;
}
pos[0] = x;
++_finish;
return pos;
}
iterator erase(iterator pos) {
assert(pos < _finish);
iterator end = pos;
while (end < _finish) {
end[0] = end[1];
++end;
}
--_finish;
return pos;
}
private:
iterator _start = nullptr; // 指向数据块的开始
iterator _finish = nullptr; // 指向有效数据的尾
iterator _endOfStorage = nullptr; // 指向存储容量的尾
};
}