0
点赞
收藏
分享

微信扫一扫

C++从入门到精通(第七篇) :vector深度剖析及模拟实现

狐沐说 2022-04-21 阅读 74
c++

vector深度剖析及模拟实现

vector的介绍及使用

vector的介绍

vector的使用

vector()(重点)

vector(size_type n, const value_type& val = value_type())

vector (const vector& x); (重点)

vector (InputIterator first, InputIterator last);

// constructing vectors
#include <iostream>
#include <vector>
int main ()
{
// constructors used in the same order as described above:
std::vector<int> first; // empty vector of ints
std::vector<int> second (4,100); // four ints with value 100
std::vector<int> third (second.begin(),second.end()); // iterating through second
std::vector<int> fourth (third); // a copy of third
// 下面涉及迭代器初始化的部分,我们学习完迭代器再来看这部分
// the iterator constructor can also be used to construct from arrays:
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
std::cout << "The contents of fifth are:";
for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}

vector iterator 的使用

begin +end(重点)

rbegin + rend

在这里插入图片描述
在这里插入图片描述

#include <iostream>
#include <vector>
using namespace std;
void PrintVector(const vector<int>& v)
{
// const对象使用const迭代器进行遍历打印
vector<int>::const_iterator it = v.begin();
while (it != v.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}
int main()
{
// 使用push_back插入4个数据
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
// 使用迭代器进行遍历打印
vector<int>::iterator it = v.begin();
while (it != v.end())
{
cout << *it << " ";
++it;
}
cout << endl;
// 使用迭代器进行修改
it = v.begin();
while (it != v.end())
{
*it *= 2;
++it;
}
// 使用反向迭代器进行遍历再打印
vector<int>::reverse_iterator rit = v.rbegin();
while (rit != v.rend())
{
cout << *rit << " ";
++rit;
}
cout << endl;
PrintVector(v);
return 0;
}

vector 空间增长问题

size

capacity

empty

resize(重点)

reserve (重点)

  • capacity的代码在vs和g++下分别运行会发现,vs下capacity是按1.5倍增长的,g++是按2倍增长的。
    这个问题经常会考察,不要固化的认为,顺序表增容都是2倍,具体增长多少是根据具体的需求定义
    的。vs是PJ版本STL,g++是SGI版本STL。
  • reserve只负责开辟空间,如果确定知道需要用多少空间,reserve可以缓解vector增容的代价缺陷问
    题。
  • resize在开空间的同时还会进行初始化,影响size。
// vector::capacity
#include <iostream>
#include <vector>
int main ()
{
size_t sz;
std::vector<int> foo;
sz = foo.capacity();
std::cout << "making foo grow:\n";
for (int i=0; i<100; ++i) {
foo.push_back(i);
if (sz!=foo.capacity()) {
sz = foo.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
}
vs:运行结果:
making foo grow:
capacity changed: 1
capacity changed: 2
capacity changed: 3
capacity changed: 4
capacity changed: 6
capacity changed: 9
capacity changed: 13
capacity changed: 19
capacity changed: 28
capacity changed: 42
capacity changed: 63
capacity changed: 94
capacity changed: 141
g++运行结果:
making foo grow:
capacity changed: 1
capacity changed: 2
capacity changed: 4
capacity changed: 8
capacity changed: 16
capacity changed: 32
capacity changed: 64
capacity changed: 128
// vector::reserve
#include <iostream>
#include <vector>
int main ()
{
size_t sz;
std::vector<int> foo;
sz = foo.capacity();
std::cout << "making foo grow:\n";
for (int i=0; i<100; ++i) {
foo.push_back(i);
if (sz!=foo.capacity()) {
sz = foo.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
std::vector<int> bar;
sz = bar.capacity();
bar.reserve(100); // this is the only difference with foo above
std::cout << "making bar grow:\n";
for (int i=0; i<100; ++i) {
bar.push_back(i);
if (sz!=bar.capacity()) {
sz = bar.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
return 0;
}

vector 增删查改

push_back(重点)

pop_back (重点)

find 查找。

insert

erase

swap

operator[] (重点)

// push_back/pop_back
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int a[] = { 1, 2, 3, 4 };
vector<int> v(a, a+sizeof(a)/sizeof(int));
vector<int>::iterator it = v.begin();
while (it != v.end()) {
cout << *it << " ";
++it;
}
cout << endl;
v.pop_back();
v.pop_back();
it = v.begin();
while (it != v.end()) {
cout << *it << " ";
++it;
}
cout << endl;
return 0;
}

vector 迭代器失效问题。(重点)

  • 对于vector可能会导致其迭代器失效的操作有:
  1. 会引起其底层空间改变的操作,都有可能是迭代器失效,比如:resize、reserve、insert、assign、
    push_back等
#include <iostream>
using namespace std;
#include <vector>
int main()
{
vector<int> v{1,2,3,4,5,6};
auto it = v.begin();
// 将有效元素个数增加到100个,多出的位置使用8填充,操作期间底层会扩容
// v.resize(100, 8);
// reserve的作用就是改变扩容大小但不改变有效元素个数,操作期间可能会引起底层容量改变
// v.reserve(100);
// 插入元素期间,可能会引起扩容,而导致原空间被释放
// v.insert(v.begin(), 0);
// v.push_back(8);
// 给vector重新赋值,可能会引起底层容量改变
v.assign(100, 8);
/*
出错原因:以上操作,都有可能会导致vector扩容,也就是说vector底层原理旧空间被释放掉,
而在打印时,it还使用的是释放之间的旧空间,在对it迭代器操作时,实际操作的是一块已经被释放的
空间,而引起代码运行时崩溃。
解决方式:在以上操作完成之后,如果想要继续通过迭代器操作vector中的元素,只需给it重新
赋值即可。
*/
while(it != v.end())
{
cout<< *it << " " ;
++it;
}
cout<<endl;
return 0;
}
  1. 指定位置元素的删除操作–erase
#include <iostream>
using namespace std;
#include <vector>
int main()
{
int a[] = { 1, 2, 3, 4 };
vector<int> v(a, a + sizeof(a) / sizeof(int));
// 使用find查找3所在位置的iterator
vector<int>::iterator pos = find(v.begin(), v.end(), 3);
// 删除pos位置的数据,导致pos迭代器失效。
v.erase(pos);
cout << *pos << endl; // 此处会导致非法访问
return 0;
}

vector模拟实现

在这里插入图片描述
在这里插入图片描述

模拟实现

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
namespace ymh
{
	template<class T>
	class vector {
	public:
		typedef	T iterator;
		vector()
			:_start(nullptr),
			_finish(nullptr),
			_endofstorage(nullptr)
		{}
		//迭代器构造
		template <class InputIterator>
		//迭代器构造
		vector(InputIterator first, InputIterator end)
			:_start(nullptr),
			_finish(nullptr),
			_endofstorage(nullptr)
		{
			while (first != end)
			{
				push_back(*first);
				first++;
			}
		}
		//拷贝构造
		vector(const vector& v)
			:_start(nullptr),
			_finish(nullptr),
			_endofstorage(nullptr)
		{
			//swap(this,v);  假如传的是const的对象 , 就交换不了了

			_start = new T[v.capacity()];
			_finish = _start + v.size();
			_endofstorage = _start + v.capacity();

			//赋值

			//memcpy(_start, v._start, sizeof(T) * v.size());  不能这样写, 会有深拷贝中的浅拷贝危险(会释放堆里的空间)
			for (size_t i = 0; i < v.size(); i++)   
			{
				_start[i] = v._start[i];
			}
		}

		//交换
		void swap(vector& v)
		{
			::swap(_start, v._start);
			::swap(_finish, v._finish);
			::swap(_endofstorage, v._endofstorage);
		}

		//运算符重载
		vector<T>& operator =(vector<T> v)
		{
			swap(v);
			return *this;
		}

		//析构函数
		~vector()
		{
			if (_start)
			{
				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;
		}

		bool empty() const
		{
			return _finish == _start;
		}

		//[]重载
		T& operator [](size_t i)
		{
			//记得断言
			assert(i < size());

			return _start[i];
	    }

		//resize
		void resize(size_t n, T t=T())
		{
			if (n < size())
			{
				_finish = _start + n;
			}
			else
			{
				if (n > capacity())
				{
					reserve(n);
				}

				while (_finish < _start + n)
				{
					*_finish = t;
					_finish++;
				}
			}
		}

		//reserve
		void reserve(size_t n)
		{
			// n<capacity 不用变化

			if (n > capacity()) //扩容
			{
				size_t sz = size();
				T* tem = new T[n];

				if (_start != nullptr)
				{
					//memcpy(tmp, _start, sz*sizeof(T)); 还是一样的问题,不能用memcpy
					for (size_t i = 0; i < sz; i++)
					{
						tem[i] = _start[i]; //如果是类,就会去调用类的构造函数,就不存在 浅拷贝 了
					}

					//记得delete之前的内存
					delete[] _start;
				}
				_start = tem;
				_finish = _start + sz;
				_endofstorage = _start + n;
			}
		}

		void push_back(T& t)
		{
			if (_finish == _endofstorage)
			{
				size_t new_capacity = capacity() == 0 ? 4 : capacity() * 2;
				reserev(new_capacity);
			}

			*_finish = t;
			_finish++:
		}

		void pop_back()
		{
			assert(!empty());

			_finish--;
		}

		void insert(iterator pos,const T& t)
		{
			if (_finish == _endofstorage)
			{
				size_t len = pos - _start; //在vector中的相对位置
				size_t new_capacity = capacity() == 0 ? 4 : capacity() * 2;
				reserve(new_capacity);

				pos = _start + len;
			}
			while (pos + 1 <= _finish)
			{
				*(pos + 1) = *pos;
				pos++;
			}
			*(_start + len) = t;
			_finish++;
		}

		iterator erase(iterator pos)
		{
			iterator it = pos + 1;
			while (it < _finish)
			{
				*(it - 1) = *it;
				it++;
			}
			_finish--;

			return pos;
		}
	private:
		iterator _start;
		iterator _finish;
		iterator _endofstorage;
	};
}

使用memcpy拷贝问题

int main()
{
bite::vector<bite::string> v;
v.push_back("1111");
v.push_back("2222");
v.push_back("3333");
return 0;
}
  • 问题分析:
  1. memcpy是内存的二进制格式拷贝,将一段内存空间中内容原封不动的拷贝到另外一段内存空间中
  2. 如果拷贝的是自定义类型的元素,memcpy即高效又不会出错,但如果拷贝的是自定义类型元素,并且
    自定义类型元素中涉及到资源管理时,就会出错,因为memcpy的拷贝实际是浅拷贝。

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

动态二维数组理解

// 以杨慧三角的前n行为例:假设n为5
void test5(size_t n)
{
	// 使用vector定义二维数组vv,vv中的每个元素都是vector<int>
	cole::vector<cole::vector<int>> vv(n);
	// 将二维数组每一行中的vecotr<int>中的元素全部设置为1
	for (size_t i = 0; i < n; ++i)
		vv[i].resize(i + 1, 1);
	// 给杨慧三角出第一列和对角线的所有元素赋值
	for (int i = 2; i < n; ++i)
	{
		for (int j = 1; j < i; ++j)
		{
			vv[i][j] = vv[i - 1][j] + vv[i - 1][j - 1];
		}
	}
}

在这里插入图片描述

  • vv中元素填充完成之后,如下图所示:
  • 在这里插入图片描述
举报

相关推荐

0 条评论