简体   繁体   English

C ++矢量模板迭代器结束函数

[英]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. 我想实现迭代器,在end()函数中遇到一个奇怪的错误。

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: 以及begin()和end()实现:

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(): 在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. 您可以通过传递*this构造迭代器,但是*this是对迭代器的引用。 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). 您的2个构造函数都引用了一个向量(而不是迭代器)。 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). (我删除了::iterator因为beginend应该是vector的方法,而不是迭代器的方法)。 Now *this would be a reference to a Vector<T> . 现在*this将是对Vector<T>的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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