RED SOFT ADAIR RED SOFT ADAIR - 29 days ago 14
C++ Question

How do you determine the last valid element in a STL-Container

If i iterate over a STL container i sometimes need to know if the current item is the last one in the sequence. Is there a better way, then doing something like this? Can i somehow convert rbegin()?

std::vector<int> myList;

// ....
std::vector<int>::iterator lastit = myList.end();
lastit--;

for(std::vector<int>::iterator it = myList.begin(); it != myList.end(); it++) {
if(it == lastit)
{
// Do something with last element
}
else
{
// Do something with all other elements
}

Answer

Try the following

std::vector<int>::iterator it2 = (++it);
if ( it2 == myList.end() ) {
  ...
}

The following should work as well

if ( it+1 == myList.end() ) {
  // it is last
  ...
}