【C++】vector 常用成员函数的模拟实现

news/2024/9/29 14:31:17 标签: c++, 算法, 开发语言

【C++】vector 常用成员函数的模拟实现

  • 1. vector 常用成员函数的模拟实现
  • 2. vector 常用成员函数实现后的测试

1. vector 常用成员函数的模拟实现

2. vector 常用成员函数实现后的测试

#include<assert.h>
#include<iostream>
#include<string>
using std::cout;
using std::endl;
using std::string;

//自定义命名空间wch
namespace wch
{
	//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<int> v(10, 1);//如果无函数vector(int n, const T& val = T()),
		//因为参数类型更匹配,会去调用vector(InputIterator first, InputIterator last)
		// 但是函数内部有解引用(*first),整形不可解引用,导致报错
		vector(size_t n, const T& val = T())
		{
			resize(n, val);
		}
		vector(int n, const T& val = T())
		{
			resize(n, val);
		}

		// [first, last)迭代器,采用区间初始化
		template<class InputIterator>
		vector(InputIterator first, InputIterator last)
		{
			while (first != last)
			{
				push_back(*first);
				++first;
			}
		}

		//由于声明时已经初始化给予了缺省参数,所以此处不写初始化列表初始化
		vector()
		{}

		//原始方法实现拷贝构造函数
		vector(const vector<T>& v)
		{
			_start = new T[v.capacity()];
			//memcpy(_start, v._start, sizeof(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)
			:_start(nullptr)
			, _finish(nullptr)
			, _endofstorage(nullptr)
		{
			reserve(v.capacity());
			for (auto e : v)
			{
				push_back(e);
			}
		}*/

		void swap(vector<T>& v)
		{
			//注意这里用的是库函数swap,因为我们这里是在自己实现vector成员函数
			std::swap(_start, v._start);
			std::swap(_finish, v._finish);
			std::swap(_endofstorage, v._endofstorage);
		}
		// v1 = v2,赋值运算符重载
		vector<T>& operator=(vector<T> v)
		{
			swap(v);
			return *this;
		}

		~vector()
		{
			if (_start)
			{
				delete[] _start;
				_start = _finish = _endofstorage = nullptr;
			}
		}

		void reserve(size_t n)
		{
			//要加判断,因为当n<capacity时,不需要做处理
			if (n > capacity())
			{
				//这里需要先保存大小,因为开辟新空间后,成员函数size里的地址_finish还指向销毁的旧空间,
				//无法正确完成_finish的更新
				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;
				_endofstorage = _start + n;
			}
		}

		//缺省参数T(),当缺省参数为自定义类型,T()为匿名对象,会去调用构造函数
		//内置类型如:int与int()无差别
		void resize(size_t n, const T& val = T())
		{
			if (n < size())
			{
				_finish = _start + n;
			}
			else
			{
				reserve(n);
				//多余有效空间用val初始化
				while (_finish != _start + n)
				{
					*_finish = val;
					++_finish;
				}
			}
		}

		void push_back(const T& x)
		{
			/*if (_finish == _endofstorage)
			{
				size_t newcapacity = capacity() == 0 ? 4 : capacity() * 2;
				reserve(newcapacity);
			}

			*_finish = x;
			++_finish;*/
			insert(end(), x);
		}

		void pop_back()
		{
			erase(--end());
		}

		size_t capacity() const
		{
			return _endofstorage - _start;
		}

		size_t size() const
		{
			return _finish - _start;
		}

		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 insert(iterator pos, const T& x)
		{
			assert(pos >= _start && pos <= _finish);

			if (_finish == _endofstorage)
			{
				size_t len = pos - _start;// 解决pos迭代器失效问题

				size_t newcapacity = capacity() == 0 ? 4 : capacity() * 2;
				reserve(newcapacity);

				// 需要更新pos,因为扩容过后pos还指向旧空间,即解决pos迭代器失效问题
				pos = _start + len;
			}

			iterator end = _finish - 1;
			while (end >= pos)
			{
				*(end + 1) = *end;
				--end;
			}

			*pos = x;
			++_finish;

			return pos;
		}

		//返回删除元素地址
		iterator erase(iterator pos)
		{
			assert(pos >= _start && pos < _finish);

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

			--_finish;

			return pos;
		}

	private:
		//给予缺省参数
		iterator _start = nullptr;
		iterator _finish = nullptr;
		iterator _endofstorage = nullptr;
	};

	void print(const vector<int>& v)
	{
		for (auto e : v)
		{
			cout << e << " ";
		}
		cout << endl;
	}

	void test_vector1()
	{
		vector<int> v1;
		v1.push_back(1);
		v1.push_back(2);
		v1.push_back(3);
		v1.push_back(4);
		v1.push_back(5);

		for (auto e : v1)
		{
			cout << e << " ";
		}
		cout << endl;

		for (size_t i = 0; i < v1.size(); i++)
		{
			v1[i]++;
		}

		for (auto e : v1)
		{
			cout << e << " ";
		}
		cout << endl;

		print(v1);
	}

	void test_vector2()
	{
		vector<int> v1;
		v1.push_back(1);
		v1.push_back(2);
		v1.push_back(3);
		v1.push_back(4);
		v1.push_back(5);
		v1.push_back(5);
		v1.push_back(5);
		v1.push_back(5);

		for (auto e : v1)
		{
			cout << e << " ";
		}
		cout << endl;

		v1.insert(v1.begin(), 100);

		for (auto e : v1)
		{
			cout << e << " ";
		}
		cout << endl;

		/*vector<int>::iterator p = v1.begin() + 3;
		v1.insert(p, 300);*/

		vector<int>::iterator p = v1.begin() + 3;
		//v1.insert(p+3, 300);

		// insert以后迭代器可能会失效(扩容)
		// 记住,insert以后就不要使用这个形参迭代器了,因为他可能失效了
		v1.insert(p, 300);

		// 高危行为
		// *p += 10;

		for (auto e : v1)
		{
			cout << e << " ";
		}
		cout << endl;
	}

	void test_vector3()
	{
		vector<int> v1;
		v1.push_back(1);
		v1.push_back(2);
		v1.push_back(2);
		v1.push_back(3);
		v1.push_back(4);
		v1.push_back(5);
		v1.push_back(6);

		for (auto e : v1)
		{
			cout << e << " ";
		}
		cout << endl;

		auto it = v1.begin();
		while (it != v1.end())
		{
			if (*it % 2 == 0)
			{
				it = v1.erase(it);
			}
			else
			{
				++it;
			}
		}

		//v1.erase(v1.begin());
		//auto it = v1.begin()+4;
		//v1.erase(it);

		 erase以后,迭代器失效了,不能访问
		 vs进行强制检查,访问会直接报错
		//cout << *it << endl;
		//++it;
		//cout << *it << endl;

		for (auto e : v1)
		{
			cout << e << " ";
		}
		cout << endl;
	}

	void test_vector4()
	{
		vector<int> v;
		v.resize(10, 0);

		for (auto e : v)
		{
			cout << e << " ";
		}
		cout << endl;

		int i = 0;
		int j = int();//i = 0;
		int k = int(1);//k = 1;
	}

	void test_vector5()
	{
		vector<int> v;
		v.push_back(1);
		v.push_back(2);
		v.push_back(3);
		v.push_back(4);
		v.push_back(5);

		vector<int> v1(v);

		for (auto e : v1)
		{
			cout << e << " ";
		}
		cout << endl;

		vector<int> v2;
		v2.resize(10, 1);

		v1 = v2;
		for (auto e : v1)
		{
			cout << e << " ";
		}
		cout << endl;
	}

	void test_vector6()
	{
		vector<string> v;
		v.push_back("111111111111111111");
		v.push_back("222222222222222222");
		v.push_back("333333333333333333");
		v.push_back("444444444444444444");
		v.push_back("555555555555555555");

		for (auto& e : v)
		{
			cout << e << " ";
		}
		cout << endl;

		vector<string> v1(v);
		for (auto& e : v1)
		{
			cout << e << " ";
		}
		cout << endl;
	}

	void test_vector7()
	{
		vector<int> v(10, 1);
		vector<string> v1(10, "1111");
		vector<int> v2(10, 1);

		for (auto e : v)
		{
			cout << e << " ";
		}
		cout << endl;

		vector<int> v3(v.begin(), v.end());
		for (auto e : v3)
		{
			cout << e << " ";
		}
		cout << endl;

		string str("hello world");
		vector<char> v4(str.begin(), str.end());
		for (auto e : v4)
		{
			cout << e << " ";
		}
		cout << endl;

		int a[] = { 16,2,77,29 };
		vector<int> v5(a, a + 4);
		for (auto e : v5)
		{
			cout << e << " ";
		}
		cout << endl;
	}
}

int main()
{
	//wch::test_vector1();
	//wch::test_vector2();
	//wch::test_vector3();
	//wch::test_vector4();
	//wch::test_vector5();
	//wch::test_vector6();
	wch::test_vector7();

	return 0;
}

http://www.niftyadmin.cn/n/5683181.html

相关文章

ENV | 5步安装 npm node(homebrew 简洁版)

1. 操作步骤 1.1 安装 homebrew /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"1.2 安装 node # 安装最新版 brew install node # 安装指定版本&#xff0c;如18 brew install node181.3 安装 nvm&#xff08…

python/爬虫技术/lxml工具介绍/XML和HTML解析

1.lxml介绍&#xff1a; lxml 是一个Python库&#xff0c;它提供了非常强大的XML和HTML解析功能。它基于libxml2和libxslt&#xff0c;是处理XML和HTML文档的首选库之一。 2.安装 首先&#xff0c;需要安装lxml库。可以通过pip来安装&#xff0c;在控制台内执行安装命令。 p…

微信小程序实战教程:轻松实现列表批量选择功能

在许多场景下&#xff0c;用户需要对列表中的多项内容进行操作&#xff0c;如批量删除、批量下载等。为了满足这一需求&#xff0c;我们需要在微信小程序中实现列表批量选择功能。具体要求如下&#xff1a; 用户可以逐个选择列表项&#xff0c;也可通过全选按钮快速选择所有列表…

第十三届蓝桥杯真题Python c组A.排列字母(持续更新)

博客主页&#xff1a;音符犹如代码系列专栏&#xff1a;蓝桥杯关注博主&#xff0c;后期持续更新系列文章如果有错误感谢请大家批评指出&#xff0c;及时修改感谢大家点赞&#x1f44d;收藏⭐评论✍ 【问题描述】 小蓝要把一个字符串中的字母按其在字母表中的顺序排列。 例如&a…

css perspective 解析及使用

概述 本文讲解 css 属性 perspective &#xff0c;这个属性的作用是设置 透视效果的观察距离。这个属性需要写在父级&#xff0c;数值越大&#xff0c;意味着你看到的页面就会越远&#xff0c;透视效果越弱。 下面是个示例&#xff1a; <!DOCTYPE html> <html lang…

手机解压软件加密指南:让文件更安全

在数字化时代&#xff0c;文件加密对于保护个人隐私和敏感信息的重要性不言而喻。随着互联网的飞速发展&#xff0c;我们的生活和工作越来越依赖于数字设备和网络。 然而&#xff0c;这也带来了一系列的安全风险&#xff0c;如黑客攻击、数据泄露等。文件加密技术成为了保护我…

第一节- C++入门

1. &#x1f680;&#x1f680;C关键字(C98) &#x1f33c;&#x1f33c;C总计63个关键字&#xff0c;C语言32个关键字 ps&#xff1a;下面我们只是看一下C有多少关键字&#xff0c;不对关键字进行具体的讲解。后面我们学到以后再细讲。 2. 命名空间 在C/C中&#xff0c;变量…

荣业食品销售费用每年上亿元:主要产品收入大降,电商占比过低

《港湾商业观察》黄懿 今年3月&#xff0c;广东荣业食品有限公司的控股公司Wing Yip Food Holdings Group Limited&#xff08;下称“荣业食品”&#xff09;向美国SEC递交了纳斯达克上市申请。 据悉&#xff0c;2023年11月&#xff0c;商务部宣布移除了一批共计55家因长期经…