实现了vector的模板,insert, erase, push_back, iterator
#include<iostream> #include<string.h> #include<stdio.h> #include <stdlib.h> using namespace std; template <typename T> class Vector{ public: int length = 0; int size = 1; T *a = (T*) malloc(sizeof(T));; T &operator[](int i){ return a[i]; } T push_back(T in){ if(length == size){ T *b; b = (T*) malloc(size*2*sizeof(T)); for(int i = 0; i < size; i++){ b[i] = a[i]; } delete(a); a = b; size *= 2; } a[length++] = in; } T* begin(){ return a; } T* end(){ return a+length; } typedef T* iterator; void clear(){ length = 0; } int insert(int num, T b){ if(num >= length) return -1; for(int i = length; i >= num; i--){ a[i] = a[i-1]; } a[num] = b; length++; return 0; } int erase(int num){ if(num > length){ return -1; } for(int i = num; i <length-1; i++){ a[i] = a[i]+1; } length --; return 0; } }; class cl{ public: int a, b; cl(){a = 0, b = 0;}; }; Vector<int> v; Vector<cl> c; int main(){ cl a; c.push_back(a); Vector<cl>::iterator It; for(It=c.begin();It!=c.end();It++) cout<<It->a<<" "<<It->b; cout<<endl; int *b = (int*) malloc(10); printf("%d", b[0]); for(int i = 0; i < 10; i++){ v.push_back(i); } for(int i = 0; i < 10; i++){ printf("%d ", v[i]); }puts(""); Vector<int>::iterator it; for(it=v.begin();it!=v.end();it++) cout<<*it<<" "; cout<<endl; printf("%d %d ", v.size, v.length); v.insert(0, 1); for(it=v.begin();it!=v.end();it++) cout<<*it<<" "; cout<<endl; printf("%d %d ", v.size, v.length); v.erase(2); v.erase(3); for(it=v.begin();it!=v.end();it++) cout<<*it<<" "; cout<<endl; printf("%d %d ", v.size, v.length); }