#pragma once
#include <memory.h>
template <typename T> class CVector
{
private:
//global pointer address
T* arr;
//vector capacity size
int capacity;
// used size in current vector value list;(!!! length)
int current;
public:
CVector()
{
arr = new T[1];
capacity = 1;
current = 0;
}
~CVector()
{
delete[] arr;
capacity = 0;
current = 0;
}
// Function to add an element at the last
void Push(T data)
{
// if current == capacity; double the vector capacity
if (IsFull()) Reserve();
// Inserting data
arr[current] = data;
current++;
}
// function to add element at any index
void Push(T data, int index)
{
if (index >= capacity)
{
printf(" index out of vector range \n");
return ;
}
else
arr[index] = data;
}
// delete end value of vector
void PopBack()
{
if (IsEmpty()) return ;
current--;
}
// delete end value of vector
void Pop( int index)
{
if (IsEmpty()) return ;
if (index >=current ) return ;
if (current == 1)
memcpy(&arr[index],&arr[index+1],sizeof(T));
else
memcpy(&arr[index],&arr[index+1],( current - index - 1)*sizeof(T));
current--;
}
// function to extract element at any index; range 0 ~ N
const T *GetElem(int index)
{
// if index is within the range
if (index < current)
return arr + index;
else
{
printf(" index out of vector range \n");
return (T *)NULL;
}
}
// get end value of vector ;range 0 ~ N
const T *Rear()
{
if (IsEmpty()) return (T *)NULL;
return arr + current - 1;
}
// get start value of vector ;range 0 ~ N
const T *Front()
{
return arr;
}
// function to get size of the vector
int Length() { return current ; }
// function to get capacity of the vector
int Vsize() { return capacity; }
bool IsFull() { return (current == capacity);}
bool IsEmpty() { return (current == 0); }
//enlarge verctor capacity, default double capacity
void Reserve(int scale = 2)
{
T* temp = new T[scale * capacity];
memcpy(temp,arr,capacity*sizeof(T));
// deleting previous array
delete[] arr;
capacity *= scale;
arr = temp;
}
CVector& operator=(const CVector& src)
{
if (&src == this)
{
return *this;
}
if (arr != NULL && src.arr != NULL)
{
delete[] arr;
arr = new T[src.capacity];
capacity = src.capacity;
current = src.current;
memcpy(arr,src.arr,capacity*sizeof(T));
}
return *this;
}
// void print()
// {
// printf("%d \n", current);
// for (int i = 0; i < current; i++) {
// printf("%d ", arr[i]);
// }
// printf("\n");
// }
c++使用模板类实现vector
于 2022-06-13 16:06:39 首次发布
本文详细探讨了如何在C++中利用模板类来实现Vector容器,包括其基本结构、内存管理和操作方法。通过实例解析,展示了模板类在创建动态数组及实现常见数组操作中的应用,有助于深化对C++模板及动态内存管理的理解。
摘要由CSDN通过智能技术生成