我正在尝试构建一个使用向量中倒数第二个元素的程序,到目前为止我已经使用过:(arr2.rbegin()+ 1)
如果我在条件中使用比较运算符,例如:
if(arr2.rbegin()+1 == true)
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息: 'no match for operator =='
Ben*_*igt 47
许多答案和评论都有正确的想法,但语法真的很难看.这里有两种表达方式.
arr2.end()[-2] // end() is past the last element, -1 for last element, -2 for second-last
arr2.rbegin()[1] // rbegin() is reverse order starting at 0 for last element, 1 for second-last
Run Code Online (Sandbox Code Playgroud)
它的工作原理是因为RandomAccessIterator的,它vector有,需要提供operator[]这样it[n]就等于*(it + n),就像为指针.
所以你问题中的代码就变得公正了
if (arr2.rbegin()[1]) // test penultimate element
Run Code Online (Sandbox Code Playgroud)
在这里查看文档
http://www.cplusplus.com/reference/vector/vector/?kw=vector
我希望您通过以下方式访问您的元素
secondToLast = myVector[myVector.size() - 2];
Run Code Online (Sandbox Code Playgroud)