gpt4 book ai didi

c++ - 与值初始化的迭代器相比,它的定义是否明确?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:31 24 4
gpt4 key购买 nike

下面的程序是否调用了未定义的行为?

#include <iostream>
#include <iterator>

int main(int argc, char* argv[])
{
for (auto it = std::istream_iterator<std::string>(std::cin);
it != std::istream_iterator<std::string>();
++it)
{
std::cout << *it << " ";
}

return 0;
}

4 year old question说他们不能比较:

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 excep- tion is an assignment of a non-singular value to an iterator that holds a singular value.

但是 C++14 标准的另一个答案是:

However, value-initialized iterators may be compared and shall compare equal to other value-initialized iterators of the same type.

最佳答案

您将两个不同的问题混为一谈。

istream_iterator 是输入迭代器,而不是前向迭代器,因此您引用的 C++14 更改根本不适用于它。您可以以这种方式比较 istream_iterator,因为它们被明确指定为允许进行此类比较。该标准说 (§24.6.1 [istream.iterator])

The constructor with no arguments istream_iterator() always constructs an end-of-stream input iterator object, which is the only legitimate iterator to be used for the end condition. [...]

Two end-of-stream iterators are always equal. An end-of-stream iterator is not equal to a non-end-of-stream iterator. Two non-end-of-stream iterators are equal when they are constructed from the same stream.

一般来说,对于前向迭代器(也包括双向和随机访问迭代器),值初始化迭代器在 C++14 中可以相互比较。 .如果您的标准库实现了它,那么您可以比较两个值初始化的迭代器。这允许您创建一个没有底层容器的空范围。但是,您仍然不允许将非奇异迭代器与值初始化迭代器进行比较。即使在 C++14 中,以下代码也具有未定义的行为:

std::list<int> l;

if(l.begin() == std::list<int>::iterator())
foo();
else
bar();

关于c++ - 与值初始化的迭代器相比,它的定义是否明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26241878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com