我目前正在学习C++,使用时遇到问题
std::string::reverse_iterator
反转字符串。尝试运行下面的函数时出现令人讨厌的编译器错误。但是,当我切换到使用时,
std::string::const_reverse_iterator
,代码编译运行成功。为什么会出现这种情况,尤其是当该语言的文档说可以声明和使用反向迭代器时?如果我需要说,在反向循环遍历字符串时从字符串中删除元素,并且想要使用反向迭代器怎么办?一个
const_reverse_iterator
在这种情况下肯定是不够的。任何帮助将非常感激。:)
std::string reverse(const std::string &str)
{
std::string::reverse_iterator r_iter;
std::string result;
for (r_iter = str.rbegin(); r_iter < str.rend(); r_iter++) {
result += (*r_iter);
}
return result;
}
其中一些错误是:
/usr/include/c++/7/bits/stl_iterator.h: In instantiation of ‘std::reverse_iterator<_Iterator>::reverse_iterator(const std::reverse_iterator<_Iter>&) [with _Iter = __gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> >; _Iterator = __gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> >]’:
chap6.cpp:40:34: required from here
/usr/include/c++/7/bits/stl_iterator.h:148:22: error: no matching function for call to ‘__gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> >::__normal_iterator(std::reverse_iterator<__gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> > >::iterator_type)’
: current(__x.base()) { }
和
/usr/include/c++/7/bits/stl_iterator.h:775:26: note: candidate expects 0 arguments, 1 provided
/usr/include/c++/7/bits/stl_iterator.h:760:11: note: candidate: constexpr __gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> >::__normal_iterator(const __gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> >&)
class __normal_iterator
^~~~~~~~~~~~~~~~~
/usr/include/c++/7/bits/stl_iterator.h:760:11: note: no known conversion for argument 1 from ‘std::reverse_iterator<__gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> > >::iterator_type {aka __gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> >}’ to ‘const __gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> >&’