I write my own vector. You need to adequately write functions like push_back() , and nothing better than this doesn’t get into your head:

 Vector<T> v(_size+1); for(int i=0;i<_size;i++) { v.at(i) = ptr[i]; } v.at(v._size-1) = value; delete[] this->ptr; ptr = v.ptr; _size = v._size; 

Advise something adequate, please. Idea rather than implementation.

    2 answers 2

    This is about the way it is done. For your implementation I can offer several improvements.
    1) Better order just a raw memory. We do not want to spend resources on the creation of objects by default? What if there is a connection to the database in the constructor, or a file is read from the disk. Resizing your vector can take a lot of time.
    You can get a piece of memory for 10 objects of type T calling ::operator new(sizeof(T) * 10);
    Std :: uninitialized_copy will help to fill the raw memory with existing objects

    2) Order the memory with a margin. Increase the size by 2-3 times. Such a move will allow you to perform memory re-ordering and copying of elements much less frequently.

    3) Use placement new instead of operator = . If you follow the first advice, then this item can be considered not as advice, but as a rule, since you cannot call the operator=() method on an uninitialized memory location. And the user of your vector is not obliged to define operator=() .
    Thus, this code:

     template<class T> class Vector{ T *items; //... void push(const T &value){ //... items[size] = value; ++size; } }; 

    should be like this:

     template<class T> class Vector{ T *items; //... void push(const T &value){ //... new (items + size)(value); ++size; } }; 

    4) With regard to the pop function, do not give the memory already occupied. It may well be useful to you. In order to free up excess memory, make a special method. In std::vector it's called shrink_to_fit

    • It may be worth adding that the implementation of shrink_to_fit allowed to do nothing at all. - αλεχολυτ

    Usually, the exponential growth of the internal array is done - this provides a constant amortized element insertion time.

    It looks like this. There is an internal array that is not necessarily full. When adding an element, if the array is filled to the end - the size of the array is multiplied by some number. Usually 2 or 1.5.

    PS There is an error in your current implementation - you are saving v.ptr , which must be destroyed in the destructor v .