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
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
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