It is simple because it does not implement the allocate class and uses a simple malloc to allocate memory.
Iterator also employs a direct value_type pointer, but retains the basic interface and method of vectors. It is helpful to understand the vector working principle.
The code and test code are as follows:
#include "stdafx.h" template < class T > class vector{enum{space_capacity = 4};//Initial capacity public:///////////////// Constructors and Destructors/////////////////////////////////////// Avoid implicit type conversions with explicit explicit vector (int size = 0): m_size (size), M_capaci
Ty (size + space_capacity) {_p = new t[m_capacity];
//copy constructor Vector (const vector & RHS): _p (NULL) {operator= (RHS);}
~vector () {delete [] _p} Operator////////////////////////// Const VECTOR & operator= (const vector & RHS) {if (thi
S!= &rhs) {//If it is itself, then no longer operate the delete [] _p;
M_size = Rhs.size ();
M_capacity = Rhs.capacity ();
_p = new t[capacity ()];
for (int k = 0; k < m_size; k++)//copy element _p[k] = Rhs._p[k];
return *this; } T & operator[] (int index) {return _p[index];}
Const T & operator[] (int index) const {return _p[index];} Pointers, iterator operations/////////////// typedef T * iterator;//replaces iterators with native pointers typedef const T * C
Onst_iterator;
Iterator begin () {return &_p[0];}
Const_iterator begin () const {return &_p[0];}
Iterator End () {return &_p[m_size];}
Const_iterator End () const {return &_p[m_size];} Insert element, popup element/////////////////// void push_back (const T & x) {if (m_size = = M_capaci
ty) Reallocate (2*m_capacity + 1);
_p[m_size++] = x;
} void Pop_back () {m_size--;} //////////////////////////////////////////////////////////////////////////////Property interface////////////////////////////////////////////////////////////////////////////////int size () const {return m _size;
int capacity () const {return m_capacity}
BOOL Empty () const {return size () = 0;} Const T & Back () const {return _p[m_size-1];} private:int m_size; The number of elements int m_capacity; Capacity T *_p; Resource//////////////////////////////////////////////////////////////////////////////////memory allocation (allocator simplification processing) pointing to new assignment/// Each time there is not enough space, you regain twice times the current capacity of space void
Resize (int newsize) {if (NewSize > M_capacity) reallocate (newsize*2);
M_size = newsize;
//Get new space, copy, release old data void reallocate (int newcapacity) {if (Newcapacity < m_size) return;
T *oldarray = _p;
_p = new t[newcapacity];
for (int k = 0; k < m_size; k++) _p[k] = oldarray[k];
m_capacity = newcapacity;
delete [] oldarray;
}
};
int main (int argc, char *argv[]) {vector<int> V;V.push_back (4);
V.push_back (5);
Vector<int>::iterator it;
For (It=v.begin (); It!=v.end (); it++) {printf ("The data is%d\n", *it);
} _getch ();
return 0;
}