How to test if an iterator is at the end of the container

E

Enselic

I have problems finding out how to test weather an iterator are at the
end of its container.

I'd like to do something like the following:

std::list<int>::iterator it = intList.begin();
while (it != intList.end()) {
if (!it.has_next())
std::cout << "This is at the last item in the container\n";

std::cout << "Number: " << *it << std::endl;

it++;
}

How would I do this the Best way? Am I looking past something obvious
here?
 
B

Berny Cantos

I use to write code like the following when facing this kind of tests:

typedef std::vector<int> MyVector;
typedef MyVector::const_iterator MyVectorCIt;

MyVector vect;
vect.push_back(10);
vect.push_back(100);
vect.push_back(1000);

MyVectorCIt it = vect.begin();
MyVectorCIt const end = vect.end();

while(it != end) {
int const& data = *it;
++it;
if(it == end) std::cout << "This is the last item: ";
std::cout << data << '\n';
}

Enselic ha escrit:
 
M

mohammad.nabil.h

Enselic ÃÑÓáÊ:
I have problems finding out how to test weather an iterator are at the
end of its container.

I'd like to do something like the following:

std::list<int>::iterator it = intList.begin();
while (it != intList.end()) {
if (!it.has_next())
std::cout << "This is at the last item in the container\n";

std::cout << "Number: " << *it << std::endl;

it++;
}

How would I do this the Best way? Am I looking past something obvious
here?

if(it == intList.end()-1)
 
E

Earl Purple

Enselic said:
I have problems finding out how to test weather an iterator are at the
end of its container.

I'd like to do something like the following:

std::list<int>::iterator it = intList.begin();
while (it != intList.end()) {
if (!it.has_next())
std::cout << "This is at the last item in the container\n";

std::cout << "Number: " << *it << std::endl;

it++;
}

How would I do this the Best way? Am I looking past something obvious
here?

There is no such thing as has_next() but you can just check if the
"next" item is end().

while ( it != intList.end() )
{
int x = *it++;

std::cout << x;
if ( it != intList.end() )
{
std::cout << ',';
}
}

If your collection is of a class you can use a reference or const
reference for a const_iterator. Thus:

while ( it != fooList.end() )
{
const foo & f = *it++;
//etc
}

Use a non-const reference if you have a non-const iterator and you are
going to modify the objects or call their non-const methods.
 

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,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top