c++ - 如何正确检查 istreambuf_iterator 是否已到达流末尾

标签 c++

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

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 ()?现在,这不是很优雅。 那是一团糟!

关于c++ - 如何正确检查 istreambuf_iterator 是否已到达流末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32994827/

相关文章:

c++ - 代码块:需要在另一个项目中编译 src

c++ - 在现有的 Delaunay 四面体化中创建并重新填充孔

c++ - Visual C++ 程序提示 net framework

c++ - 函数如何访问矩阵?

c++ - 包装 PropertySheet;如何处理回调?

C++ 无法推导出模板参数

c++ - 无限图算法

c++ - 如何使用 "new"而不是 malloc 分配内存?

c++ - 是否存在与用于 Java 的 Google Gson/XStream 一样简单的 C++ 序列化库?

c++ - 用于在 C++ 中抽象数据库访问的开源库?