迭代器的默认值是什么?

发布于 2024-09-12 06:00:29 字数 210 浏览 2 评论 0原文

对于我正在使用的任何 STL 容器,如果我使用迭代器的默认构造函数声明一个迭代器(此特定容器类型),则迭代器将被初始化为什么?

例如,我有:

std::list<void*> address_list;
std::list<void*>::iterator iter;

iter 将初始化为什么?

For any STL container that I'm using, if I declare an iterator (of this particular container type) using the iterator's default constructor, what will the iterator be initialised to?

For example, I have:

std::list<void*> address_list;
std::list<void*>::iterator iter;

What will iter be initialised to?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

剑心龙吟 2024-09-19 06:00:29

按照惯例,容器的“NULL 迭代器”用于指示没有结果,与 container.end() 的结果进行比较。

 std::vector<X>::iterator iter = std::find(my_vec.begin(), my_vec.end(), x);
 if (iter == my_vec.end()) {
     //no result found; iter points to "nothing"
 }

然而,由于默认构造的容器迭代器不与任何特定容器关联,因此它没有好的值。因此,它只是一个未初始化的变量,对其进行的唯一合法操作是为其分配一个有效的迭代器。

 std::vector<X>::iterator iter;  //no particular value
 iter = some_vector.begin();  //iter is now usable

对于其他类型的迭代器,情况可能并非如此。例如,在 istream_iterator 的情况下,默认构造的迭代器表示(比较等于)已到达输入流的 EOF 的 istream_iterator。

By convention a "NULL iterator" for containers, which is used to indicate no result, compares equal to the result of container.end().

 std::vector<X>::iterator iter = std::find(my_vec.begin(), my_vec.end(), x);
 if (iter == my_vec.end()) {
     //no result found; iter points to "nothing"
 }

However, since a default-constructed container iterator is not associated with any particular container, there is no good value it could take. Therefore it is just an uninitialized variable and the only legal operation to do with it is to assign a valid iterator to it.

 std::vector<X>::iterator iter;  //no particular value
 iter = some_vector.begin();  //iter is now usable

For other kinds of iterators this might not be true. E.g in case of istream_iterator, a default-constructed iterator represents (compares equal to) an istream_iterator which has reached the EOF of an input stream.

赴月观长安 2024-09-19 06:00:29

默认构造函数将迭代器初始化为单值

迭代器还可以具有不与任何序列关联的奇异值。
[示例:在声明未初始化的指针x之后(与int* x;一样),
x 必须始终被假定为具有奇异值的指针。 —结束示例]
大多数表达式的结果对于奇异值都是未定义的
[24.2.1 §5]< /p>

The default constructor initializes an iterator to a singular value:

Iterators can also have singular values that are not associated with any sequence.
[ 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. — end example ]
Results of most expressions are undefined for singular values
[24.2.1 §5]

一城柳絮吹成雪 2024-09-19 06:00:29

迭代器未初始化,就像 int x; 声明一个未初始化的整数一样。它没有正确定义的值。

The iterator is not initialized, just as int x; declares an integer which isn't initialized. It does not have a properly defined value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文