C++ 为什么可以';我在使用STL列表时是否使用此回文函数?
我制作了一个回文函数,允许我使用任何容器类型,它对string、vector和deque都有效,但是当我制作了一个STL列表并尝试运行代码时,我得到了下面的错误,我无法理解这意味着什么以及该怎么做C++ 为什么可以';我在使用STL列表时是否使用此回文函数?,c++,c++11,stl,palindrome,auto,C++,C++11,Stl,Palindrome,Auto,我制作了一个回文函数,允许我使用任何容器类型,它对string、vector和deque都有效,但是当我制作了一个STL列表并尝试运行代码时,我得到了下面的错误,我无法理解这意味着什么以及该怎么做 Severity Code Description Project File Line Suppression State Error C2676 binary '-': 'std::_List_const_iterator<std::_List_val<s
Severity Code Description Project File Line Suppression State
Error C2676 binary '-': 'std::_List_const_iterator<std::_List_val<std::_List_simple_types<_Ty>>>' does not define this operator or a conversion to a type acceptable to the predefined operator homework4 C:\...\Source.cpp 9
Severity Code Description Project File Line Suppression State
Error C3536 'itr1': cannot be used before it is initialized homework4 C:\...\Source.cpp 9
Severity Code Description Project File Line Suppression State
Error C2676 binary '<': 'std::_List_const_iterator<std::_List_val<std::_List_simple_types<_Ty>>>' does not define this operator or a conversion to a type acceptable to the predefined operator homework4 C:\...\Source.cpp 9
Severity Code Description Project File Line Suppression State
Error C2100 illegal indirection homework4 C:\...\Source.cpp 10
严重性代码描述项目文件行抑制状态
错误C2676二进制“-”:“std::\u List\u const\u iterator”未定义此运算符或到预定义运算符homework4 C:\…\Source.cpp 9可接受的类型的转换
严重性代码说明项目文件行抑制状态
错误C3536“itr1”:在初始化家庭作业4 C:\…\Source.cpp 9之前无法使用
严重性代码说明项目文件行抑制状态
错误C2676二进制“标准容器std::list具有双向迭代器。此表达式中使用的运算符
itr1 = s.end() - 1
itr < itr1
是为随机访问迭代器定义的。您可以使用头
中声明的标准函数std::prev
,如
itr1 = std::prev( s.end() )
但是,在任何情况下,函数都是无效的,因为函数的用户通常可以通过一个空容器。在这种情况下,表达式std::prev(s.end())
具有未定义的行为
并且没有为双向迭代器定义运算符<。所以这个表达式
itr1 = s.end() - 1
itr < itr1
程序输出为
true
true
true
true
true
如果需要,可以将该函数专用于随机访问迭代器。将s.end()-1
替换为std::prev(s.end())
。前者需要一个随机访问迭代器,而列表迭代器不是。对于第二种情况,使用反向迭代器与s.rbegin()
和s.rend()
。此外,将来,使用std::next
,std::advance
,std::distance
,等等。如果您需要以通用方式执行类似操作。@IgorTandetnik列表迭代器的itr
也会有问题,因为@AdrianMole为True。需要像itr!=itr1&&itr!=std::next(itr1)
非常巧妙的循环条件!可能需要专门化const char*
转换为std::string
或std::string\u视图