反向迭代器不会编译

时间:2010-07-01 14:51:10

标签: c++

我正在尝试编译一个反向迭代器但是我这样做的尝试给了一个可怕的混乱。代码的最小例子是......

#include <iostream>
#include <vector>
#include <algorithm>

class frag {
    public:
        void print (void) const;
    private:
        std::vector<int> a;
};

void frag::print (void) const
{
    for (std::vector<int>::reverse_iterator iter = a.begin ();
         iter                                   != a.end ();
         ++iter) {
        std::cout << *iter << std::endl;
    }
}

并尝试编译它会产生以下内容......

In file included from /usr/include/c++/4.4/bits/stl_algobase.h:69,
             from /usr/include/c++/4.4/bits/char_traits.h:41,
             from /usr/include/c++/4.4/ios:41,
             from /usr/include/c++/4.4/ostream:40,
             from /usr/include/c++/4.4/iostream:40,
             from frag.cpp:1:
/usr/include/c++/4.4/bits/stl_iterator.h: In constructor ‘std::reverse_iterator<_Iterator>::reverse_iterator(const std::reverse_iterator<_Iter>&) [with _Iter = __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >, _Iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >]’:
frag.cpp:14:   instantiated from here
/usr/include/c++/4.4/bits/stl_iterator.h:134: error: no matching function for call to ‘__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >::__normal_iterator(__gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >)’
/usr/include/c++/4.4/bits/stl_iterator.h:686: note: candidates are: __gnu_cxx::__normal_iterator<_Iterator, _Container>::__normal_iterator(const _Iterator&) [with _Iterator = int*, _Container = std::vector<int, std::allocator<int> >]
/usr/include/c++/4.4/bits/stl_iterator.h:683: note:                 __gnu_cxx::__normal_iterator<_Iterator, _Container>::__normal_iterator() [with _Iterator = int*, _Container = std::vector<int, std::allocator<int> >]
/usr/include/c++/4.4/bits/stl_iterator.h:669: note:                 __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >::__normal_iterator(const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)

昨天有一个关于这个问题的问题,但我认为这不是一个模板。如果在本地以类似的方式声明向量,则非常高兴。 (在Ubuntu 10.4上使用g ++)。

任何人都知道我应该做什么?

4 个答案:

答案 0 :(得分:19)

您需要使用const_reverse_iteratorprintconst函数,因此aconst)和a.rbegin()以及{{1}而不是a.rend()begin()

答案 1 :(得分:3)

可能导致代码出现问题的两件事:

  1. 您的print()函数已声明为const,因此您(可能需要或应该)使用const_reverse_iterator

  2. 您是从reverse_iteratornormal_iterator

  3. 创建std::vector<T>::begin()

答案 2 :(得分:2)

您必须将 reverse 迭代器分配给反向迭代器。比较相同。可以使用方法rbeginrend

获取反向迭代器
for (std::vector<int>::reverse_iterator iter = a.rbegin(); iter != a.rend(); ++iter);

编辑(完整性) 正如其他人所注意到的那样,这里也需要const_reverse_iterator。

答案 3 :(得分:1)

上述答案已经指出,在这种情况下需要map const_reverse_iterator / rbegin

除此之外,一个好的做法是使用rendcrbegin(在C ++ 11中引入)明确表明你要求迭代器的const版本,因为{{ 1}}函数是const。