Click to See Complete Forum and Search --> : How to get the iterator of the last element?


Franz
July 18th, 2002, 04:00 AM
Except using rbegin, are there any other stl functions for getting the iterator of the last element? vector::back just gives me the reference of that.

Graham
July 18th, 2002, 04:11 AM
--c.end().

Only works for Bidirectional containers but, then, so does c.rbegin().

cup
July 18th, 2002, 04:30 AM
Graham,

Isn't c.end () one past the last one?

Graham
July 18th, 2002, 04:36 AM
That's why I applied the decrement operator to it.

cup
July 18th, 2002, 04:41 AM
Sorry - I thought the -- was a comment. Ada is getting me confused.

Franz
July 18th, 2002, 04:56 AM
If i use decrement operator on the end iterator, will the end iterator "itself" decrease by 1?

Just like
int i = 0;
--i;
Then i will become -1.

May be this is a silly question, sorry. :(

Graham
July 18th, 2002, 05:27 AM
No.

end() simply returns a one-past-the-end iterator and it's that that you decrement.


std::vector<int> v;

// fill v...

std::vector<int>::iterator i = --v.end();

// i now points to the last element in v.


It would probably be a good idea to check that the container is not empty(), though. Decrementing end() then could cause problems.

Franz
July 18th, 2002, 07:18 AM
Oops, VC6 can't compile it.

error C2105: '--' needs l-value

Graham
July 18th, 2002, 07:36 AM
OK. Get the interator into a variable and decrement that:

(whatever)::iterator i = c.end();
--i;

Franz
July 18th, 2002, 07:51 AM
Thanks:)

Alexey B
July 18th, 2002, 11:10 AM
You can also write(c.end() - 1)for vector iterators.