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

S

Simon

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
 
J

joecook

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?

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
 
S

Simon

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top