我可以检查 C++ 迭代器是否为 null 吗?

Can I check a C++ iterator against null?

我在使用向量迭代器时遇到问题。我在一些地方读到过,检查空迭代器是不可能的,检查迭代器的常用方法是在搜索后根据 vector.end() 检查它。例如:

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();

问题是容器可能是空的。使用迭代器,我不能 return null 来指示容器为空或搜索失败。我可以 return vector::end(),但是 cplusplus.com 说:

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

然后对于 vector::begin() 它说:

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

所以如果我有一个空容器,vector::end() 和 vector::begin() 指向同一个地方,我认为我不能取消引用它,我什至都没有确保它指向分配的内存。

编辑:感谢大家。正如您迭代的那样,vector::end() 或 vector::begin() 不会取消引用迭代器,我可以安全地检查 vector::end().

不,您不能检查 NULL,因为它不是指针。 Return 并检查 animalList.end()。只有当迭代器不等于 end() 时才应该取消引用它。

您不需要检查迭代器是否为空,因为它永远不会。您需要检查返回的迭代器是否与容器的 end() 位置不同。如果是,您可以通过 *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.

不,检查 if(myIt != container.end()) 不是取消引用迭代器。迭代器取消引用是通过 *myIt 完成的,这意味着获取迭代器指向的对象的值。从同一个容器检查迭代器到其他迭代器总是安全的,取消引用不指向容器元素的迭代器是不安全的。

就这样检查

auto it = findInList( someInfo );

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