vector使用+模拟实现
Posted Bug程序员小张
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vector使用+模拟实现相关的知识,希望对你有一定的参考价值。
目录
vector介绍
vector是表示可变大小数组的序列式容器。vector采用连续的空间存储元素,大小通过动态增长的方式改变,元素的访问比较高效。
常见接口
构造函数
//构造函数测试 void Vector_Test1() //无参构造 vector<int> v1; //初始化n个val构造 vector<int> v2(5, 10); //拷贝构造 vector<int> v3(v2); //迭代器区间构造 vector<int> v4(v3.begin(), v3.end());
迭代器
如上图所示,正向迭代器的begin指向首元素的迭代器位置,end指向末尾元素的下一个位置,【左闭,右开)。反向迭代器正好相反。
//迭代器测试 void Vector_Test2() vector<int> vv= 1,2,3,4,5,6,7,8,9 ; //vector<int>::iterator it = vv.begin(); auto it = vv.begin(); cout << "正向迭代:>" << endl; while (it != vv.end()) cout << *it << " "; it++; cout << endl; auto rit = vv.rbegin(); cout << "反向迭代:>" << endl; while (rit != vv.rend()) cout << *rit << " "; rit++; cout << endl;
容量操作
简单接口测试:
//容量测试 void Vector_Test3() vector<int> vv(10,985); cout <<"size:>" << vv.size() << endl; cout << "capacity:>" << vv.capacity() << endl; cout << "empty? :>" << vv.empty() << endl;
resize和reserve分析:
resize和reserve都有的共同点就是不会进行缩容,给我空间可以,想缩容,没门!
resize:
void Printf(vector<int> vv) auto it = vv.begin(); while (it != vv.end()) cout << *it << " "; it++; cout << endl; void Vector_Test4() vector<int> vv = 1,2,3,4,5,6,7,8,9 ; vv.resize(15,1); cout << "newsize>size:" << endl; cout << "size:" << vv.size() << endl; cout << "capacity:" << vv.capacity() << endl; Printf(vv); vv.reserve(20); vv.resize(20, 100); cout << "newsize在容量范围内:" << endl; cout << "size:" << vv.size() << endl; cout << "capacity:" << vv.capacity() << endl; Printf(vv); vv.resize(5); cout << "newsize<size:" << endl; cout << "size:" << vv.size()<<endl; cout << "capacity:" << vv.capacity() << endl; Printf(vv);
reserve:新容量大扩容,新容量下不变!
void Vector_Test5() vector<int> vv = 1,2,3,4,5; cout << "----------容量增加,扩容-----------" << endl; cout << "capacity:" << vv.capacity() << endl; vv.reserve(10); cout << "newcapacity:" << vv.capacity() << endl; cout << "----------容量减少,不变-----------" << endl; cout << "capacity:" << vv.capacity() << endl; vv.reserve(5); cout << "newcapacity:" << vv.capacity() << endl;
默认扩容机制测试: vs下测试,默认按照1.5倍扩容!
void TestVectorExpand() size_t sz; vector<int> v; //记录每次扩容后的容量大小 sz = v.capacity(); int cnt = 1; for (int i = 0; i < 100; ++i) v.push_back(i); if (sz != v.capacity()) sz = v.capacity(); cout << "第" << cnt++<<"次扩容: " << sz << '\\n';
c++11提供的接口,调用后缩容。
void Vector_Test6() vector<int> vv; cout << "capacity:" << vv.capacity() << endl; vv.reserve(20); cout << "capacity:" << vv.capacity() << endl; vv.resize(10); vv.shrink_to_fit(); cout << "shrink_to_fit_capacity:" << vv.capacity() << endl;
元素访问
上述两个接口的功能类似,在底层实现上【】检查越界的方式是断言,在release断言会失效。at接口底层检查越界的方式是抛异常,使用上可读性没有【】直观,因为我们比较习惯【】的使用。
void Vector_Test7() vector<int> vv = 1,2,3,4,5,6,7,8,9 ; cout <<"[]:>" << vv[3] << endl; cout <<"at:>"<< vv.at(5) << endl;
增删查改
assign:将新内容赋给向量,替换其当前内容,并相应地修改其大小。
void Vector_Test8() vector<int> vv = 1,2,3,4,5,6,7,8,9 ; vector<int> vv2; vv2.assign(vv.begin(), vv.end()); Printf(vv); vv.assign(12, 1); Printf(vv);
上述剩余接口都比较常用,需要注意的是,在使用插入或者删除后如果后序还要使用it,需要重写接收一下insert和erase返回的迭代器位置,否则会出现迭代器失效的问题,后面会详细讨论。
void Vector_Test9() vector<int> vv = 1,2,3,4,5,6,7,8,9 ; auto it = vv.begin(); vv.insert(it,5); vv.insert(it, 5); vv.insert(it, 5); vv.insert(it, 5); it++; *it = 10;
查找接口统一使用算法中(algorithm)的查找,vector容器中并没有提供查找接口。
模拟实现
模拟实现要点图解
整体代码
template<class T>
class vector
public:
typedef T* iterator;
typedef const T* const_iterator;
iterator being()
return _start;
iterator end()
return _finish;
const_iterator begin() const
return _start;
const_iterator end()const
return _finish;
T& operator[](size_t pos)
return _start[pos];
T& operator[](size_t pos) const
return _start[pos];
//无参构造
vector()
:_start(nullptr)
, _finish(nullptr)
, _end_of_storage(nullptr)
//初始化n个val
vector(size_t n, const T& val = T())
:_start(nullptr)
, _finish(nullptr)
, _end_of_storage(nullptr)
reserve(n);
for (int i = 0; i < n; ++i)
push_back(val);
vector(int n, const T & val = T())
:_start(nullptr)
, _finish(nullptr)
, _end_of_storage(nullptr)
reserve(n);
for (int i = 0; i < n; ++i)
push_back(val);
//代代器区间
template <class InputIterator>
vector(InputIterator first, InputIterator last)
:_start(nullptr)
, _finish(nullptr)
, _end_of_storage(nullptr)
while (first != last)
push_back(*first);
++first;
//拷贝构造
vector(const vector<T>& v)
:_start(nullptr)
, _finish(nullptr)
, _end_of_storage(nullptr)
//调用构造
vector<T> tmp(v.begin(),v.end());
//将构造好的交换给this
swap(tmp);
//赋值,这里不能给引用,不然赋值变成交换
vector<T>& operator=(vector<T> v)
swap(v);
return *this;
//析构
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()
delete[] _start;
_start = _finish = _end_of_storage = nullptr;
//扩容
void reserve(size_t n)
if (n > capacity())
//扩容
T* tmp = new T[n];
size_t oldsize = size();
if (_start)
//浅拷贝
//memcpy(tmp, _start, sizeof(T) * oldsize);
for (size_t i = 0; i < oldsize; i++)
tmp[i] = _start[i];
delete[] _start;
//_start的地址变成了新的
_start = tmp;
_finish = tmp + oldsize;//_finish的计算要注意
_end_of_storage = tmp + n;
//调整size
void resize(size_t n, T val = T())
if(n>capacity())
//扩容
reserve(n);
if (n > size())
//填数据
while (_finish < _start + n)
* _finish = val;
++_finish;
else
//删除数据
_finish = _start + n;
//返回容量
size_t capacity() const
return _end_of_storage - _start;
//返回size
size_t size() const
return _finish - _start;
//尾插
void push_back(const T& val)
if (_finish == _end_of_storage)
//扩容
size_t newcapacity = capacity() == 0 ? 4 : 2 * capacity();
reserve(newcapacity);
_end_of_storage = _start + newcapacity;
*_finish = val;
_finish++;
//尾删
void pop_back()
assert(size()>0);
--_finish;
//迭代器失效问题
//插入
iterator insert(iterator pos,const T& val)
assert(pos >= _start);
assert(pos <= _finish);
if (_finish == _end_of_storage)
//记录下pos到 ——start的距离
size_t len = pos - _start;
size_t newcapacity = capacity() == 0 ? 4 : 2 * capacity();
reserve(newcapacity);
//扩容后会导致迭代器的失效问题
pos = _start + len;
//向后挪动数据
iterator end = _finish - 1;
while (end >= pos)
*(end+1) = *end;
--end;
*pos = val;
++_finish;
return pos;
//删除
iterator erase(iterator pos)
assert(pos >= _start);
assert(pos < _finish);
iterator begin = pos + 1;
while (begin < _finish)
*(begin - 1) = *(begin);
++begin;
--_finish;
return pos;
//清除数据
void clear()
_finish = _start;
//判断空
bool empty() const
return _start == _finish;
private:
iterator _start;
iterator _finish;
iterator _end_of_storage;
;
迭代器失效问题
内部失效
外部失效
int main()
vector<int> vv;
auto it = vv.begin();
vv.insert(it, 1);
//读
cout << *it << endl;
//cout << (*it)++ << endl;
return 0;
上述代码中用的是库中的vector,但是同样存在迭代器失效的问题,调用insert接口插入数据后会发生扩容,外部迭代器指向的空间已经被释放了,此时该迭代器已经失效了,当对该位置进行读写操作时就会出现错误!
如果仍然要再次使用it的话,在使用前对it重新赋值就好了。
深浅拷贝问题
void reserve(size_t n)
if (n > capacity())
//扩容
T* tmp = new T[n];
size_t oldsize = size();
if (_start)
//浅拷贝
//memcpy(tmp, _start, sizeof(T) * oldsize);
delete[] _start;
//_start的地址变成了新的
_start = tmp;
_finish = tmp + oldsize;//_finish的计算要注意
_end_of_storage = tmp + n;
void testcopy()
zxy::vector<string> v1;
string ss("abc");
v1.push_back(ss);
v1.push_back(ss);
v1.push_back(ss);
v1.push_back(ss);
//第5次插入发生扩容
v1.push_back(ss);
问题分析:
当第5次插入数据,发生了扩容。string是自定义类型,并且有资源的申请。浅拷贝完成后,手动的delete[] _start。当析构函数调用时会在次释放该空间,所以这里不能用浅拷贝。
解决办法:换成深拷贝
//扩容
void reserve(size_t n)
if (n > capacity())
//扩容
T* tmp = new T[n];
size_t oldsize = size();
if (_start)
for (size_t i = 0; i < oldsize; i++)
tmp[i] = _start[i];
delete[] _start;
//_start的地址变成了新的
_start = tmp;
_finish = tmp + oldsize;//_finish的计算要注意
_end_of_storage = tmp + n;
C++ vector基本使用与模拟实现
vector的使用与模拟实现
一、基本接口的调用
#include<iostream>
#include<vector>
#include<string>
#include<stdio.h>
#include<algorithm>
using namespace std;
void test_vector1()
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
//遍历vector的几种方式
for (size_t i = 0; i < v.size(); i++) //1、下标+[]
cout << v[i] << " ";
cout << endl;
vector<int>::iterator it = v.begin(); //2、迭代器
while (it != v.end())
cout << *it << " ";
it++;
cout << endl;
for (auto e : v) //范围for
cout << e << " ";
cout << endl;
vector<int>::reverse_iterator rit = v.rbegin();
while (rit != v.rend())
cout << *rit << " ";
rit++;
cout << endl;
vector<int> v2(++v.begin(), --v.end()); //利用迭代器区间构造对象————区间左闭右开
string s("hello world");
vector<char> v3(s.begin(), s.end()); //其它容器的迭代器只要类型匹配同样适用
vector<int> v4;
v4.assign(s.begin(), s.end()); //assign接口类似————中文意思为分配
void test_vector2()
vector<int> v;
v.reserve(10);//开空间改变容量,但不初始化
//错误访问——————下标引用操作符会检查插入位置是否合法,即小于_size
//for (size_t i = 0; i < 10; i++)
//
// v[i] = i;
//
//正确访问
for (size_t i = 0; i < 10; i++)
v.push_back(i);
v.resize(20);//开空间+初始化
void test_vector3()
int a[] = 1,2,3,4,5 ;
vector<int> v(a, a + 5);
//头插
v.insert(v.begin(), 0); //第一个参数传入的是迭代器
//在2前面插入
vector<int>::iterator pos = find(v.begin(), v.end(), 2); //find函数位于算法库中algorithm
if (pos != v.end()) //查找失败会返回end位置的迭代器
v.insert(pos, 20);
//sort排序
sort(v.begin(), v.end());
sort(v.begin(), v.end(), greater<int>()); //greater<int>是一个仿函数类,需要调用库函数是functional
void test_vector4()
int a[] = 1,2,3,4,5 ;
vector<int> v(a, a + 5);
//头删
v.erase(v.begin()); //参数传入下标位置的迭代器,或迭代器区间
//删除2
vector<int>::iterator pos = find(v.begin(), v.end(), 2);
if (pos != v.end())
v.erase(pos);
int main()
test_vector1();
test_vector2();
test_vector3();
test_vector4();
return 0;
vector的重要知识点再回顾
迭代器因insert失效(erase同理)
结论:在insert(pos, x)以后,都认为pos迭代器失效了,不要再去使用pos了。
原因:1、插入可能导致扩容,而异地扩容会导致pos变成“野指针”。
2、就算不扩容,pos指向的位置意义已经变化了,所以也认为失效。
解决方案:insert的返回值是指向新插入元素的迭代器位置。利用返回值赋值给pos即可。
模拟实现vector
template<class T>
class vector
public:
typedef T* iterator;
typedef const T* const_iterator;
vector()
:_start(nullptr)
,_finish(nullptr)
,_endofstorage(nullptr)
vector(const vector<T>& v)
:_start(nullptr)
, _finish(nullptr)
, _endofstorage(nullptr)
reserve(v.capacity());
for (const auto e : v)
push_back(e);
template <class InputIterator>
vector(InputIterator first, InputIterator last)
:_start(nullptr)
, _finish(nullptr)
, _endofstorage(nullptr)
while (first != last)
push_back(*first);
first++;
~vector()
delete[] _start;
_start = _finish = _endofstorage = nullptr;
iterator begin()
return _start;
iterator end()
return _finish;
const_iterator begin()const
return _start;
const_iterator end()const
return _finish;
size_t capacity() const
return _endofstorage - _start;
size_t size() const
return _finish - _start;
void reserve(size_t num)
if (num > capacity())
size_t sz = size();
T* tmp = new T[num];
memcpy(tmp, _start, sz * sizeof(T));
_start = tmp;
_finish = _start + sz;
_endofstorage = _start + num;
iterator insert(iterator pos, const T& num)
assert(pos >= begin() && pos <= end());
if (_finish == _endofstorage)
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 = num;
_finish++;
return pos;
iterator erase(iterator pos)
assert(pos >= begin() && pos < end());
//删除指定下标的数据,并把其后的数据依次向前挪动
iterator it = pos + 1;
while (it != end())
*(it - 1) = *it;
it++;
--_finish;
return pos;
void push_back(const T& num)
insert(end(), num);
T& operator[](size_t i)
assert(i < size());
return *(_start + i);
void swap(vector<T>& v)
std::swap(v._start, _start);
std::swap(v._finish, _finish);
std::swap(v._endofstorage, _endofstorage);
vector<T>& operator=(vector<T> v)
swap(v);
return *this;
void resize(size_t n, const T& val = T())
//开的空间小于size(把超出范围的舍弃)介于size和capacity(初始化_finish以后的空间)
//大于capacity(要重新开空间,并且初始化_finish以后的空间)
if (n <= size())
_finish = _start + n;
else
if (n > capacity())
reserve(n);
while (_finish < _start + n)
*_finish = val;
_finish++;
private:
iterator _start;
iterator _finish;
iterator _endofstorage;
;
vector模拟实现中reserve的bug
更深层次的浅拷贝引发的问题
解决方案:利用string类重载的=实现深拷贝
以上是关于vector使用+模拟实现的主要内容,如果未能解决你的问题,请参考以下文章