我在使用矢量迭代器时遇到问题。我在几个地方读到过,检查空迭代器是不可能的,检查迭代器的常用方法是在搜索后根据 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 许可协议
您不需要检查迭代器是否为空,因为它永远不会。您需要检查返回的迭代器是否与容器的
end()
位置不同。如果是,您可以通过*it
安全地取消对迭代器的引用。不,检查
if(myIt != container.end())
不是取消引用迭代器。迭代器取消引用是通过*myIt
完成的,这意味着获取迭代器指向的对象的值。从同一个容器检查迭代器到其他迭代器总是安全的,取消引用不指向容器元素的迭代器是不安全的。