用C++简单写一个Vector
#include <iostream>
using namespace std;
template<class T>
class x_vector{
private:
T* data;
int size;
int capacity;
public:
x_vector(int init_capacity = 0){
size = 0;
capacity = init_capacity;
data = new T[capacity];
}
void expansion(int capacity);
void push_back(const T& item);
void pop_back();
void clear();
int get_size();
T& operator[] (int index);
};
template<class T>
void x_vector<T>::clear(){
size = 0;
}
template<class T>
T& x_vector<T>::operator[](int index){
return data[index];
}
template<class T>
int x_vector<T>::get_size(){
return size;
}
template<class T>
void x_vector<T>::expansion(int new_capacity){
T* old = data;
data = new T[new_capacity];
for(int i = 0;i < size;i++){
data[i] = old[i];
}
capacity = new_capacity;
delete[] old;
}
template<class T>
void x_vector<T>::push_back(const T& item){
if(size == capacity){
expansion(2*capacity + 1);
}
data[size++] = item;
}
template<class T>
void x_vector<T>::pop_back(){
size--;
}
int main(){
x_vector<double> arr(0);
arr.push_back(2.0);
arr.push_back(3.0);
double x = arr[1];
system("pause");
return 0;
}