#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<set>
#include<queue>
#include<unordered_map>
#include<cmath>
using namespace std;
template<class T>
class CArray
{
int st = 32;
int size, temp;
T* ptr;
public:
CArray(int s = 0);
CArray(CArray<T>& a);
~CArray();
void push_back(T v);
void resize(int v);
void Resize(int v);
CArray<T>& operator=(const CArray<T>& a) ;
int length() { return max(size, temp); };
T& operator [](int i)
{
return ptr[i];
}
};
template<class T>
CArray<T>::CArray(int s)
{
resize(s);
}
template<class T>
CArray<T>::CArray(CArray<T>& a)
{
if (!a.ptr)
{
ptr = NULL;
size = 0;
return;
}
ptr = new T[a.size];
memcpy(ptr, a.ptr, sizeof(T) * a.size);
size = a.size;
}
template<class T>
CArray<T>& CArray<T>::operator=(const CArray<T>& a)
{
if (ptr == a.ptr)
return *this;
if (a.ptr == NULL)
{
if (ptr) delete[]ptr;
ptr = NULL;
size = 0;
return *this;
}
if (size < a.size)
{
if (ptr) delete[]ptr;
ptr = new T[a.size];
}
memcpy(ptr, a.ptr, sizeof(T) * a.size);
size = a.size;
return *this;
}
template<class T>
CArray<T>::~CArray()
{
if (ptr) delete[]ptr;
}
template<class T>
void CArray<T>::resize(int v)
{
if (v == 0)
ptr = NULL;
else
{
T* temptr = new T[v];
memcpy(temptr, ptr, sizeof(T) * size);
delete[]ptr;
ptr = temptr;
while (size < v)
{
ptr[size++] = 0;
}
}
}
template<class T>
void CArray<T>::Resize(int v)
{
T* temptr = new T[v];
memcpy(temptr, ptr, sizeof(T) * size);
delete[]ptr;
ptr = temptr;
}
template<class T>
void CArray<T>::push_back(T v)
{
if (ptr)
{
if (size < st)
ptr[size++] = v;
else
{
st = st * 2;
Resize(st);
ptr[size++] = v;
}
}
else
{
ptr = new T[st];
ptr[size++] = v;
}
}
int main()
{
CArray<double>a;
for (int i = 0; i < 64; i++)
{
a.push_back(i + 0.3);
}
CArray<int>b;
for (int i = 0; i < 64; i++)
{
b.push_back(i);
}
for (int i = 0; i < a.length(); i++)
{
cout << a[i] << " ";
}
cout << endl;
CArray<int>q(73);
q[1] = 3;
for (int i = 0; i < q.length(); i++)
{
cout << q[i] << " ";
}
cout << endl;
CArray<int>f;
f = q;
for (int i = 0; i < f.length(); i++)
{
cout << f[i] << " ";
}
CArray<int>e(f);
for (int i = 0; i < e.length(); i++)
{
cout << e[i] << " ";
}
}
vector 插入实现
最新推荐文章于 2024-02-22 12:07:03 发布