自己动手写vector

    最近学习c++的STL,把STL中的vector自己写了一下,写的过程中对c++进行学习。

主要的几个模块:

 (1)构造析构函数、拷贝构造和赋值函数(类的几个基本函数)
(2)增加、删除函数
(3)遍历函数
(4)大小及判空函数
(5)其它(swap或者assign)

// MyVector.cpp : 定义控制台应用程序的入口点。
/*******************我的Vector实现*********************************
**功能:自己动手写stl中的vector
**作者:谢凡凡
****************************************************/
#include "stdafx.h"
#include <iostream>
#include <assert.h>

using namespace std;

//vector类模板
template <class T>
class MyVector
{
public:
	typedef T* iterator;           //迭代器类型
	typedef T* pointer;
	typedef T & reference;
//构造函数
	MyVector():start(0),endx(0),end_of_storage(0),nsize(0),ncapacity(0){}             //列表初始化  默认的构造函数
	MyVector(int nSize,const T& val)                     //n个元素,且初始化为val
	{
		if (!nSize)
		{
			start = 0;
			endx = 0;
			end_of_storage = 0;
			nsize = 0;
			ncapacity = 0;
		}
		else
		{
			int iTotalLen = 1;
			while (iTotalLen < nSize)                     //空间大小是2倍增长
			{
				iTotalLen *= 2;
			}
			start = new T[iTotalLen];                     //申请空间
			iterator start_cc = start;
			endx = start + nSize;
			end_of_storage = start + iTotalLen;
			nsize = nSize;
			ncapacity = iTotalLen;
			while(nSize--)
			{
				*start_cc++ = val;
			}
		}
	}
	MyVector(int nSize)                                       //n个元素,初始化为0
	{
		if (!nSize)
		{
			start = 0;
			endx = 0;
			end_of_storage = 0;
			nsize = 0;
			ncapacity = 0;
		}
		else
		{
			int iTotalLen = 1;
			while (iTotalLen < nSize)
			{
				iTotalLen *= 2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值