在模板类中使用向量迭代器

时间:2012-04-13 05:21:31

标签: c++ templates stl iterator

我正在尝试在我正在创建的模板类中创建一个矢量迭代器。以下是故障代码。

void editor<T>::insert()
{   
        typedef typename std::vector<T>::const_iterator itr;
        itr it;
        it = this->buffer.begin();

        for(int i = 0; i < line_num -1; ++i)
        {   
            ++it;
        }

        this->buffer.insert(it, user_text);
        std::cout << "Cool, Your new line has been inserted." << '\n';
    }
    std::cout << '\n';
}

我收到以下编译错误:

error: no match for ‘operator=’ in ‘it = ((editor<std::basic_string<char> >*)this)->editor<std::basic_string<char> >::buffer.std::vector<_Tp, _Alloc>::begin [with _Tp = std::vector<std::basic_string<char>, std::allocator<std::basic_string<char> > >, _Alloc = std::allocator<std::vector<std::basic_string<char>, std::allocator<std::basic_string<char> > > >, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<std::vector<std::basic_string<char>, std::allocator<std::basic_string<char> > >*, std::vector<std::vector<std::basic_string<char>, std::allocator<std::basic_string<char> > >, std::allocator<std::vector<std::basic_string<char>, std::allocator<std::basic_string<char> > > > > >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = std::vector<std::basic_string<char>, std::allocator<std::basic_string<char> > >*]()’ 

我感觉编译器与我上面的typedef语句混淆了,但这就是我看到声明正确迭代器的方式,但由于某种原因它无法正常工作。有什么想法吗?

1 个答案:

答案 0 :(得分:7)

如果bufferstd::vector< std::vector<T> >,则buffer.begin()std::vector< std::vector<T> >::iteratorconst_iterator,因此您的typedef不匹配。