简体   繁体   中英

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?

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM