如何正确检查 istreambuf_iterator 是否已到达流结尾

How do I properly check that a istreambuf_iterator has reached end-of-stream

在我读到的标准中,您必须创建一个默认迭代器才能知道迭代器是否已到达流末尾。我认为它变得非常丑陋,难道没有任何预定义的符号或等效符号可以帮助我们吗?

The default-constructed std::istreambuf_iterator is known as the end-of-stream iterator. When a valid std::istreambuf_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator.

这是代码示例:

std::istreambuf_iterator<char> it(is);
std::istreambuf_iterator<char> end;

    if (it != end) { break;}

为什么迭代器没有命名的函数,即 hasNext() 或 isEndOfStream()

isn't there any predefined symbol or equivalent that could help us here?

是的。

you have to create a deafult iterator to be able to know if the iterator has reach end-of stream

在这里!

Why doesn't the iterator has a function named, i.e. hasNext() or isEndOfStream()

作为哨兵的单数迭代器其实还是很优雅的。它不会在库中引入任何新名称,它允许我们使用 startend 迭代器编写通用代码,而这些迭代器不关心您正在迭代的是什么类型的东西。这对于标准算法来说非常重要。

void bar(const char c);

template <typename Iterator>
void foo(Iterator start, Iterator end)
{
   for (Iterator it = start; it != end; ++it)
      bar(*it);
}

void version_1()
{
   std::istreambuf_iterator<char> start(std::cin);
   std::istreambuf_iterator<char> end;
   foo(start, end);
}

void version_2()
{
   std::vector<char> v{0,1,2,3,4,5};
   foo(v.begin(), v.end());
}

想象一下,如果对于容器,您有 startend,但对于流,您有 start 和对 start.hasNext() 的调用?现在,这不是很优雅。 那是一团糟!