Reputation: 333
I want to know if the following check is necessary:
std::list<int> myList;
.....
for (std::list<int>::iterator itr = myList.begin(); itr != myList.end(); ++itr)
{
if (itr != NULL) // Is This Check Necessary?
{
// DO SOMTHING.
}
}
I have seen this check in some places and I'm wondering if that is a necessary check. Maybe this check is necessary if the list is an input to a function?
Thanks, Ofer.
Upvotes: 3
Views: 426
Reputation: 445
I think there's no way to test if an iterator is uninitialized, But you can initialize iterator to the end() of the container as a default value.
std::list<int>::iterator itr = yourlist.end();
//
if (itr != yourlist.end())
{
//doSomething
}
Upvotes: 1
Reputation: 11
It's unnecessary to check.If the myList is empty,then myList.begin() equals to myList.end()
Upvotes: 1
Reputation: 195
instead you can use new range based for loops (C++11), so you dont need to deal with iterator checking.
std::list<int> YourList;
for( auto z : YourList ) {
//
std::cout << z; // z is int
// amazing codes and fun :)
//
}
Upvotes: 1
Reputation: 1804
No, it is an unnecessary check.
You might want to check *itr != nullptr
, if the list held some kind of pointers.
Upvotes: 4