简体   繁体   English

迭代器使用end()持续std :: vector的元素 -

[英]Iterator to last element of std::vector using end()--

I have a std::vector and I want the iterator to the last element in the vector; 我有一个std::vector ,我希望iterator到向量中的最后一个元素; I will be storing this iterator for later use. 我将存储此迭代器供以后使用。

NOTE: I want an iterator reference to it, not std::vector::back . 注意:我想要一个迭代器引用它,而不是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::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),有没有更好的方法呢?

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() . 你无意中只是返回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. 虽然如果向量是空的,但无论如何都没有最后一个元素。

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. 请注意,如果vector<T>::iterator只是T* (这将是有效的),则上面的第一个表单是格式错误的。 The second two work regardless, so are preferable. 第二个工作无论如何,所以更可取。

The way you are doing it will give you the wrong iterator because post increment will not change the value until after the assignment. 你这样做的方式会给你错误的迭代器,因为在赋值之后post增量不会改变值。

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. 请记住首先检查容器是否为空,以便迭代器存在于有效范围内。

You have rbegin that does what you need 你有rbegin做你需要的

cplusplus reference cplusplus参考

auto last = container.rbegin();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM