Zeb*_*ish 12 c++ pointers iterator vector nullptr
我在使用矢量迭代器时遇到了麻烦.我在一些地方读过,检查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();
Run Code Online (Sandbox Code Playgroud)
问题是容器可能是空的.使用迭代器,我不能返回null以指示容器为空或搜索失败.我可以返回vector :: end(),但cplusplus.com说:
If the container is empty, vector::end() function returns the same as vector::begin()
Run Code Online (Sandbox Code Playgroud)
然后对于vector :: begin()它说:
If the container is empty, the returned iterator value shall not be dereferenced.
Run Code Online (Sandbox Code Playgroud)
所以,如果我有一个空容器,vector :: end()和vector :: begin()指向同一个地方,我认为我不能取消引用它,我甚至不确定它是否指向已分配的内存.
编辑:感谢大家.当你迭代出来时,vector :: end()或vector :: begin()不要取消引用迭代器,我可以安全地检查vector :: end().
paw*_*dac 17
您不需要检查迭代器是否为null,因为它永远不会.您需要检查返回的迭代器是否与容器end()位置不同.如果是,您可以安全地取消引用迭代器*it.
如果容器为空,则不应取消引用返回的迭代器值.所以,如果我有一个空容器,vector :: end()和vector :: begin()指向同一个地方,我认为我不能取消引用它,我甚至不确定它是否指向已分配的内存.
不,检查if(myIt != container.end())它不解除引用迭代器.迭代器取消引用*myIt,意味着获取迭代器所指向的对象的值.检查来自同一容器的其他迭代器的迭代器总是安全的,取消引用迭代器而不指向容器元素是不安全的.