C++ 向量中倒数第二个元素的代码是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18539954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:00:28  来源:igfitidea点击:

What is the code for the second to last element in a vector

c++

提问by Person

I am trying to build a program that uses the second to last element in a vector, so far I've used: (arr2.rbegin()+1)

我正在尝试构建一个使用向量中倒数第二个元素的程序,到目前为止我已经使用过:(arr2.rbegin()+1)

If I use a comparison operator in a conditional such as:

如果我在条件中使用比较运算符,例如:

if(arr2.rbegin()+1 == true) 

I get an error message: 'no match for operator =='

我收到一条错误消息: 'no match for operator =='

回答by Ben Voigt

Many of the answers and comments have the right idea but really ugly syntax. Here are two nice ways to express that.

许多答案和评论都有正确的想法,但语法非常丑陋。这里有两种很好的表达方式。

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

Demo: http://ideone.com/2cZeUq

演示:http: //ideone.com/2cZeUq

It works because RandomAccessIterator, which vectorhas, is required to provide operator[]such that it[n]is equivalent to *(it + n), just like for pointers.

它的工作原理是因为RandomAccessIterator的,它vector有,需要提供operator[]这样it[n]就等于*(it + n),就像为指针。

So the code in your question becomes just

所以你问题中的代码就变成了

if (arr2.rbegin()[1]) // test penultimate element

回答by Sam I am says Reinstate Monica

looking at the documentation here

在此处查看文档

http://www.cplusplus.com/reference/vector/vector/?kw=vector

http://www.cplusplus.com/reference/vector/vector/?kw=vector

I'd expect you to access your element by

我希望您通过以下方式访问您的元素

secondToLast = myVector[myVector.size() - 2];

回答by Rahul Tripathi

You can try doing like this:-

您可以尝试这样做:-

if(*(arr2.rbegin()+1))

回答by Gavin Perkins

It depends on what you mean by "second to last element". Take the following iterator definition...

这取决于您所说的“倒数第二个元素”是什么意思。采用以下迭代器定义...

vector<int>::iterator it = arr2.end();

it--; 
it--;

You have to decriment the iterator twice because when you declare the iterator to "point" to the end, it actually references the location AFTER the last element in the vector.

您必须将迭代器减量两次,因为当您将迭代器声明为“指向”末尾时,它实际上引用了向量中最后一个元素之后的位置。

Dont forget that when you want the value that the iterator points to, you have to dereference it. like so...

不要忘记,当您想要迭代器指向的值时,您必须取消引用它。像这样...

cout << *it;