c++ - STL 迭代器上下文中的奇异值和非奇异值是什么?

标签 c++ pointers stl iterator standards

C++ 标准 (2003) 的第 24.1/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 nonsingular.

我无法真正理解以粗体显示的文字?

  • 什么是奇异值和非奇异值?它们是如何定义的?在哪里?
  • 如何以及为什么可解引用的值总是是非奇异的?

最佳答案

如果我理解正确,迭代器的奇异值本质上等同于未分配的指针。它是一个尚未初始化为指向任何地方的迭代器,因此没有明确定义的元素正在迭代。例如,声明一个未设置为指向某个范围元素的新迭代器时,会将该迭代器创建为单个迭代器。

正如规范的部分暗示的那样,单数迭代器是不安全的,并且不能对它们使用任何标准迭代器操作,例如递增、赋值等。您所能做的就是为它们分配一个新值,希望将它们指向有效数据。

我认为有这个定义的原因是这样的陈述

set<int>::iterator itr;

可以被规范允许,同时具有标准化的含义。这里的“奇异性”一词可能指的是奇异性的数学定义,在不太正式的情况下也称为“不连续性”。

关于c++ - STL 迭代器上下文中的奇异值和非奇异值是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5441893/

相关文章:

c++ - 防止 QObject* 隐式转换为 bool : prevent 'Multiple constructor' warning

c++ - 如何找到正在运行的进程的物理套接字 ID/编号?

c++ - 从 const 指针到指针的转换

c - while(fgets) 之后的 memset()

c - 不在 C 中转换指针会导致问题吗?

c++ - 匹配不区分大小写的整个字符串

c++ - std::map 插入的可疑结果

带有栅栏和获取/释放的 C++ memory_order

c++ - STL 中的双端队列到底是什么?

c++ - 从函数结构成员获取函数地址