C++ 迭代器使用 end()--std::vector 的最后一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37017302/
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
Iterator to last element of std::vector using end()--
提问by Quark
I have a std::vector
and I want the iterator
to the last element in the vector; I will be storing this iterator for later use.
我有一个std::vector
,我想要iterator
向量中的最后一个元素;我将存储此迭代器以备后用。
NOTE: I want an iterator reference to it, not std::vector::back
. Because I want to be able to compute the index of this object from the std::vector::begin
later on.
注意:我想要对它的迭代器引用,而不是std::vector::back
. 因为我希望能够从std::vector::begin
以后计算这个对象的索引。
The following is my logic to get the iterator to the last element:
以下是我将迭代器获取到最后一个元素的逻辑:
std::vector<int> container;
std::vector<int>::iterator it = container.end()--;
Since std::vector::end
has O(1) time complexity, is there a better way to do this?
由于std::vector::end
具有 O(1) 时间复杂度,有没有更好的方法来做到这一点?
回答by Barry
I think you mean either:
我想你的意思是:
std::vector<int>::iterator it = --container.end();
std::vector<int>::iterator it = container.end() - 1;
std::vector<int>::iterator it = std::prev(container.end());
You're unintentionally just returning end()
. But the problem with all of these is what happens when the vector is empty, otherwise they're all do the right thing in constant time. Though if the vector is empty, there's no last element anyway.
你无意中刚回来end()
。但是所有这些的问题是当向量为空时会发生什么,否则它们都会在恒定时间内做正确的事情。尽管如果向量为空,则无论如何都没有最后一个元素。
Also be careful when storing iterators - they can get invalidated.
存储迭代器时也要小心 - 它们可能会失效。
Note that if vector<T>::iterator
is just T*
(which would be valid), the first form above is ill-formed. The second two work regardless, so are preferable.
请注意,如果vector<T>::iterator
只是T*
(这将是有效的),则上面的第一种形式是格式错误的。后两者不管用,所以更可取。
回答by Galik
The way you are doing it will give you the wrong iterator because post incrementwill not change the value until afterthe assignment.
你这样做的方式会给你错误的迭代器,因为后增量不会在赋值之后改变值。
There is always this:
总有这样的:
auto it = std::prev(container.end());
Remember to check first that the container is not empty so your iterator exists in a valid range.
请记住首先检查容器是否为空,以便您的迭代器存在于有效范围内。
回答by dau_sama
You have rbegin
that does what you need
你有rbegin
你需要的
auto last = container.rbegin();