我可以针对 null 检查 C 迭代器吗?

新手上路,请多包涵

我在使用矢量迭代器时遇到问题。我在几个地方读到过,检查空迭代器是不可能的,检查迭代器的常用方法是在搜索后根据 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();

问题是容器可能是空的。使用迭代器,我无法返回 null 以指示容器为空或搜索失败。我可以返回 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()。

原文由 Zebrafish 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 613
2 个回答

您不需要检查迭代器是否为空,因为它永远不会。您需要检查返回的迭代器是否与容器的 end() 位置不同。如果是,您可以通过 *it 安全地取消对迭代器的引用。

如果容器为空,则返回的迭代器值不应被取消引用。因此,如果我有一个空容器,vector::end() 和 vector::begin() 指向同一个地方,我认为我不能取消引用它,我什至不确定它是否指向分配的内存。

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

原文由 paweldac 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 Mikel F 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题