Enselic ha escrit:
> 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?

Advertisements

Guest

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?

Enselic wrote:
> 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.

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!