Search code examples
c++constructoriterator

C++ vector template iterator end function


I have a task to write template vector with separate description. I want to realize iterator and I have a strange error at end() function.

I have two constructors:

template <class T>
Vector<T>::iterator::iterator(Vector<T>& v): vector(v), index(0){}

template <class T>
Vector<T>::iterator::iterator(Vector<T>& v, bool): vector(v), index(v.getSize()){}

and begin() and end() realization:

template <class T>
typename Vector<T>::iterator Vector<T>::iterator::begin()
{
    return iterator(*this);
}

template <class T>
typename Vector<T>::iterator Vector<T>::iterator::end()
{
    return iterator(*this, true);
}

In main():

 Vector<int>::iterator it(vec);        
        for(Vector<int>::iterator start = it.begin(); start != it.end(); ++start)
        {
            std::cout << *start << std::endl;
        }

I have an error:

F:\Vector\vector.cpp:281: ошибка: no matching function for call to 'Vector<int>::iterator::iterator(Vector<int>::iterator&, bool)'
     return iterator(*this, true);

It seems, I don't understand something. What's wrong?


Solution

  • Here:

    template <class T>
    typename Vector<T>::iterator Vector<T>::iterator::begin()
    {
        return iterator(*this);
    }
    
    template <class T>
    typename Vector<T>::iterator Vector<T>::iterator::end()
    {
        return iterator(*this, true);
    }
    

    You construct an iterator by passing *this, but *this is a reference to an iterator. And as the compiler says, you didn't define any iterator constructor which takes a reference to an iterator as parameter. Your 2 construtors both take a reference to a vector (not an iterator). You should do this:

    template <class T>
    typename Vector<T>::iterator Vector<T>::begin()
    {
        return iterator(*this);
    }
    
    template <class T>
    typename Vector<T>::iterator Vector<T>::end()
    {
        return iterator(*this, true);
    }
    

    (I removed ::iterator because begin and end are supposed to be vector's methods, and not iterator's). Now *this would be a reference to a Vector<T>.