最近学习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