Implementing a Custom Vector Class in C++

Vector Class Framework

The basic framework for our custom vector implementation inculdes three main pointers:

template<class T>
class vector
{
private:
    iterator _start = nullptr; // Points to beginning of data
    iterator _finish = nullptr; // Points to end of valid data
    iterator _endOfStorage = nullptr; // Points to end of storage capacity
};

Core Functionality Implementation

1. Constructro and Destructor

vector() {}

~vector()
{
    delete[] _start;
    _start = _finish = _endOfStorage = nullptr;
}

2. Push Back Operation

void push_back(const T& x)
{
    if (_finish == _endOfStorage)
    {
        size_t new_capacity = capacity() == 0 ? 4 : (capacity() * 2);
        reserve(new_capacity);
    }
    *(_finish) = x;
    ++_finish;
}

3. Memory Management

void reserve(size_t n)
{
    if (n > capacity())
    {
        T* new_space = new T[n + 1];
        size_t current_size = size();
        
        for(size_t i = 0; i < current_size; ++i)
        {
            new_space[i] = _start[i];
        }
        
        delete[] _start;
        _start = new_space;
        _finish = _start + current_size;
        _endOfStorage = _start + n;
    }
}

4. Element Access

T& operator[](size_t index)
{
    assert(index < size());
    return _start[index];
}

5. Iterator Implementation

typedef T* iterator;
typedef const T* const_iterator;

iterator begin() { return _start; }
iterator end() { return _finish; }

6. Insert Operation

iterator insert(iterator position, const T& value)
{
    assert(position >= _start && position <= _finish);
    
    size_t offset = position - _start;
    
    if (_finish == _endOfStorage)
    {
        reserve(capacity() == 0 ? 4 : capacity() * 2);
        position = _start + offset;
    }
    
    for(iterator it = _finish; it > position; --it)
    {
        *it = *(it - 1);
    }
    
    *position = value;
    ++_finish;
    return position;
}

7. Erase Opertaion

iterator erase(iterator position)
{
    assert(position >= _start && position < _finish);
    
    for(iterator it = position; it < _finish - 1; ++it)
    {
        *it = *(it + 1);
    }
    
    --_finish;
    return position;
}

8. Copy Constructor

vector(const vector<T>& source)
    : _start(nullptr), _finish(nullptr), _endOfStorage(nullptr)
{
    reserve(source.capacity());
    for(size_t i = 0; i < source.size(); ++i)
    {
        push_back(source[i]);
    }
}

9. Assignment Operator

vector<T>& operator=(vector<T> source)
{
    swap(source);
    return *this;
}

void swap(vector<T>& other)
{
    std::swap(_start, other._start);
    std::swap(_finish, other._finish);
    std::swap(_endOfStorage, other._endOfStorage);
}

Tags: C++ Data Structures vector STL Templates

Posted on Mon, 01 Jun 2026 01:36:51 +0000 by murali