🔒 Locked
std::vector[vector.size() - 1]
Advertisement
Original Post
If I have a std vector of variables, for example: std::vector vec; how do I get the last one - the equilivant to: vec[vec.size()-1] ? I remember reading that there was a better way. Thanks.
Quote:
Original post by Dave
myVector.end() - 1;
*edit: Ignore me, I have been living a lie.
CM
[Edited by - Conner McCloud on August 16, 2006 2:29:04 PM]
My code is a mess. I used to use vec.end[-1], then I discovered vec.back() [smile]
Out of interest (Because I'm too lazy to look for myself), what does std::vector do if you call back() and it's empty? The same as accessing an invalid index with operator[] or .at()?
Out of interest (Because I'm too lazy to look for myself), what does std::vector do if you call back() and it's empty? The same as accessing an invalid index with operator[] or .at()?
Quote:
Original post by Evil Steve
Out of interest (Because I'm too lazy to look for myself), what does std::vector do if you call back() and it's empty? The same as accessing an invalid index with operator[] or .at()?
a.back() returns *--a.end() for vector a [ISO/IEC 14882:1998(E) 23.1.1 Table 68]. If the vector is empty, the results will be undefined since in that case a.begin == a.end(), and one-before-the-beginning of a vector is undefined.
Quote:
Original post by Conner McCloud Quote:
Original post by Dave
myVector.end() - 1;
vector::end() returns an invalid iterator. You can't legally use it to reach a valid one.
CM
That's not true. It's perfectly fine to go from end to another iterator through iterator operations. This holds for all container types.
Quote:
Original post by Dave Quote:
Original post by Conner McCloud Quote:
Original post by Dave
myVector.end() - 1;
vector::end() returns an invalid iterator. You can't legally use it to reach a valid one.
CM
So that's why none of my code ever works. Bugger.
I'M A NOOB!
In that case, it probably does work. Which is why its so important not to get into the habit of doing it. A more complex structure [say, std::set] may not work that way.
*edit: Or maybe I'm mistaken...
CM
Quote:
Original post by Polymorphic OOP Quote:
Original post by Conner McCloud Quote:
Original post by Dave
myVector.end() - 1;
vector::end() returns an invalid iterator. You can't legally use it to reach a valid one.
CM
That's not true. It's perfectly fine to go from end to another iterator through iterator operations. This holds for all container types.
I stand corrected, and have edited my post accordingly. I was under the impression that i-- required i be dereferenceable, but apparently it does not.
CM
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement