Can I check a C++ iterator against null?

末鹿安然 提交于 2019-12-12 10:34:50

问题


I'm having trouble with vector iterators. I've read in a few places that checking for null iterators isn't possible, and that the usual way to check iterators is to check it against vector.end() after a search. So for example:

vector< Animal* > animalList;

vector<Animal*>::iterator findInList(const type_info& type)
{
    // Loop through list of Animals, if Dog found, return iterator to it
}

auto it = findInList(typeid(Dog));
// With a pointer I can check if it's null, but with an iterator I have to check against animalList.end();

The problem is that the container could be empty. With an iterator I can't return null to indicate the container's empty or the search failed. I can return vector::end(), but cplusplus.com says:

If the container is empty, vector::end() function returns the same as vector::begin()

and then for vector::begin() it says:

If the container is empty, the returned iterator value shall not be dereferenced.

So if I have an empty container, vector::end() and vector::begin() point to the same place, I don't think I can dereference it, and I'm not even sure it's pointing to allocated memory.

Edit: Thanks to everyone. As you have iterated out, vector::end() or vector::begin() do not dereference the iterator, I can safely check against vector::end().


回答1:


You don't need to check if iterator is null, because it will never be. You need to check if returned iterator is different from containers end() position. If it is, you can safely dereference iterator by *it.

If the container is empty, the returned iterator value shall not be dereferenced. So if I have an empty container, vector::end() and vector::begin() point to the same place, I don't think I can dereference it, and I'm not even sure it's pointing to allocated memory.

No, checking if(myIt != container.end()) it not dereferencing the iterator. Iterator dereference is *myIt, which means getting value of object, that iterator is pointing to. It's always safe to check iterators to other iterators from the same container, it's unsafe to dereference iterator not pointing to containers elements.




回答2:


No, you can't check against NULL because it is not a pointer. Return and also check against animalList.end(). Only when the iterator is not equal to end() should you dereference it.




回答3:


Just check like this

auto it = findInList( someInfo );

if ( it == animalList.end() ) std::cout << "not found";


来源:https://stackoverflow.com/questions/41352941/can-i-check-a-c-iterator-against-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!