C++ 迭代器的默认值是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3395180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:45:34  来源:igfitidea点击:

What is an iterator's default value?

c++stldefaultcontainersiterator

提问by The Void

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?

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

For example, I have:

例如,我有:

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

What will iter be initialised to?

iter 将被初始化为什么?

采纳答案by UncleBens

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

按照惯例,用于表示没有结果的容器的“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"
 }

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_iteratorwhich has reached the EOF of an input stream.

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

回答by fredoverflow

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]

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

回答by JesperE

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

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