user548936
user548936

Reputation: 113

using c++, how do I implement itetator to my own container class so i can use something like std::sort()

i'm trying to learn how to implement iterator functionality in my own container class so i can use something like std::sort()

i've created my own container class. how do i now add iterator functionality, like begin(), end(), ...

template <class T> class MyVector { public:
    MyVector() : m_DataPtr(NULL), m_nSize(0), m_nAllocated(0) {}
    ~MyVector() { delete m_DataPtr; }
    size_t Size() const { return m_nSize; }
    void PushBack(const T &data);

private:
    T *m_DataPtr;
    size_t m_nSize;
    size_t m_nAllocated; };

//******************************

template <class T> void MyVector<T>::PushBack(const T &data) {
    if (m_nSize == m_nAllocated)
    {
        m_nAllocated = (m_nAllocated+1) *2;
        T *tmp = new T[m_nAllocated];
        if (!tmp)
            return;

        // transfer data from ptr to tmp
        for (size_t i = 0; i < m_nSize; i++)
            tmp[i] = m_DataPtr[i];

        // delete[] ptr and set it to tmp
        delete[] m_DataPtr;
        m_DataPtr = tmp;
    }
    m_DataPtr[m_nSize++] = data;
}

Upvotes: 1

Views: 154

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63830

You may implement begin() and end() by adding this to your class definition.

T* begin() { return m_DataPtr; }
T* end() { return m_DataPtr + m_nSize; }

Your use of contiguous memory allows raw pointers to function as iterators.

Upvotes: 1

Related Questions