c++ - 如何检查迭代器是否已初始化?

标签 c++ iterator

如果我为迭代器使用默认构造函数,如何检查它是否稍后被分配?

对于指针,我可以这样做:

int *p = NULL;
/// some code
if ( NULL == p ) {
  // do stuff
}

如何为迭代器执行上述操作? 有可能吗?

#include <iostream>
#include <list>

int main ()
{
    std::list<int>::iterator it;

  if ( NULL == it ) // this fails
  {
      std::cout<<"do stuff" << std::endl;
  }
}

最佳答案

我设法在当前标准 (c++03) 中找到了这一点。 24.1 p 5 告诉:

Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding container. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable. Iterators can also have singular values that are not associated with any container. [Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer. ] Results of most expressions are undefined for singular values; the only exception is an assignment of a non-singular value to an iterator that holds a singular value. In this case the singular value is overwritten the same way as any other value. Dereferenceable values are always non- singular.

(强调我的)

所以答案是:不,不可能。

关于c++ - 如何检查迭代器是否已初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6954949/

相关文章:

c++ - front() 和 back() 在队列中分配值的目的? (C++)

c++ - C++ 中的迭代器开始/结束与 :collection

c++ - 为什么有些 libstdc++ 迭代器有 operator++ 但没有 operator+?

java - Xpath 在 java 中使用 NodeIterator

C++ 使用 std::sort 为非常小的 std::vector 抛出 std::bad_alloc 异常

c++ - 指针 : p++ & p+1

c++ - 函数省略结构

c++ - 尝试遍历 C++ 中的对象指针队列

python - 如何检测两个Python迭代器产生相同的项目?

c++ - 计算结构 vector 中的匹配项