一、普通类实现变长数组
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
class Vector
{
private:
int len;
int* items;
public:
Vector(int _len) : len(_len)
{
items = new int[len];
}
~Vector()
{
delete[] items; items = nullptr;
}
void resize(int new_len)
{
if (new_len <= len) return;
int* tmp = new int[new_len];
for (int i = 0; i < len; i++) tmp[i] = items[i];
delete[] items;
items = tmp;
len = new_len;
}
int size()
{
return len;
}
int& operator[] (int index)
{
if (index >= len) resize(index + 1);
return items[index];
}
const int& operator[] (int index) const
{
return items[index];
}
};
int main()
{
Vector list(3);
for (int i = 0; i < 10; i++) list[i] = i;
for (int i = 0; i < 10; i++) cout << list[i] << ' ';
cout << endl;
cout << list.size() << endl;
return 0;
}
二、模板类
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
template <class T>
class Vector
{
private:
int len;
T* items;
public:
Vector(int _len) : len(_len)
{
items = new T[len];
}
~Vector()
{
delete[] items; items = nullptr;
}
void resize(int new_len)
{
if (new_len <= len) return;
T* tmp = new T[new_len];
for (int i = 0; i < len; i++) tmp[i] = items[i];
delete[] items;
items = tmp;
len = new_len;
}
int size()
{
return len;
}
T& operator[] (int index)
{
if (index >= len) resize(index + 1);
return items[index];
}
const T& operator[] (int index) const
{
return items[index];
}
};
int main()
{
Vector<string> list(3);
for (int i = 0; i < 5; i++) list[i] = to_string(i + 25);
for (int i = 0; i < 5; i++) cout << list[i] << ' ';
cout << endl;
cout << list.size() << endl;
return 0;
}