gpt4 book ai didi

c++ - 反向迭代器不会编译

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:50:16 27 4
gpt4 key购买 nike

我正在尝试编译一个反向迭代器,但我这样做的尝试造成了可怕的困惑。代码的最小示例是...

#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> > >&)

昨天有一个关于这个主题的问题,但我认为这不一样,因为它不是模板。如果一个 vector 在本地以类似的方式声明,它会很高兴。 (Ubuntu 10.4 上的 g++)。

有人知道我该怎么做吗?

最佳答案

您需要使用const_reverse_iterator(print 是一个const 函数,所以aconst) 和 a.rbegin()a.rend() 而不是 begin()end().

关于c++ - 反向迭代器不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3158922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com