Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

the last element in a container, (std::vector, std:map ... )

66 views
Skip to first unread message

Simon

unread,
May 31, 2009, 11:36:26 AM5/31/09
to
Hi,

Using a vector as a example, if I have a something like:

std::vector<int> myNumbers;
// ... add items to the vector

and I iterate thru them all,

for( std::vector<int>::const_iterator it = myNumbers.begin();
it != myNumbers.end();
++it )
{
if( it == myNumbers.begin() )
{
// do some stuff with the first element
}
else if( it == /* last element in the container */ )
// <------
{
// do something because this is the last element.
}
else
{
// do something else for elements that are neither first nor last.
}
}

In the code above, how do I tell that this is the last element in the
container?

Many thanks

Simon

joe...@gmail.com

unread,
May 31, 2009, 11:47:54 AM5/31/09
to

For a random access iterator like vector, you can use end()-1

I don't see the need to check for begin() and back() when iterating
through a vector everytime through the loop, since you know the first
one will be the first one, and the last one will be the last one.

Why not:
if (!myNumbers.empty())
{


std::vector<int>::const_iterator it = myNumbers.begin();

std::vector<int>::const_iterator backIter = myNumbers.end()-1
doBeginStuff(it)
for(++it; it != backIter; ++it)
{
// doMiddleStuff;
}
doBackStuff(it);
}

Joe

Simon

unread,
May 31, 2009, 11:57:47 AM5/31/09
to
> For a random access iterator like vector, you can use end()-1

That's what I thought, I wonder if there would be a sizeable performance
degradation if I check for begin and end all the time.

> I don't see the need to check for begin() and back() when iterating
> through a vector everytime through the loop, since you know the first
> one will be the first one, and the last one will be the last one.

My code was over simplified, in the real implementation I do some common
tasks as well as 'specialized' tasks for the begin/end stuff.
But I guess it would be trivial to add a function to do the common work.

Thanks

Simon

0 new messages