【发布时间】:2017-05-12 04:46:47
【问题描述】:
我在使用矢量迭代器时遇到了问题。我在几个地方读到过,检查空迭代器是不可能的,检查迭代器的常用方法是在搜索后根据 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()。
【问题讨论】:
-
返回一个空向量的迭代器。当调用者在迭代器上循环时,循环将立即结束,并且他们永远不会取消对迭代器的引用。
-
您是否试图避免暴露您在内部使用的容器,因此犹豫是否提供一种方法让用户根据您的容器本身的
end检查返回值?跨度> -
迭代器不是指针。
-
“所以如果我有一个空容器......我认为我不能取消引用它” 如果您返回可能为空的指针,情况也是如此.
-
@jaggedSpire,现在必须。好吧,我希望该功能尽可能多地处理。我想从我理解的答案中,我可以得到与 vector::end() 相同的行为检查,也就是说,与返回指针并检查 nullptr 相同。
标签: c++ pointers vector iterator nullptr