取自 A Tour of C++
迭代器的概念可以应用到输入输出,istream_iterator是一个输入迭代器,读取元素调用>>,默认构造表示EOF,当读取失败或到达末尾时就等于这个默认构造
ostream_iterator是一个输出迭代器,赋值时调用<<,自增是一个空操作,为的是满足兼容性,构造函数有一个可选的参数表示分隔符
1 2 3 4 5 6 7 8 9 10 #include <iterator> #include <iostream> #include <set> #include <string> int main () { std::set<std::string> b {std::istream_iterator<std::string>{std::cin}, std::istream_iterator<std::string>{}}; copy (b.begin (), b.end (), std::ostream_iterator<std::string>{std::cout, "\n" }); }
在引入range后有istream_view<T>{is}这样的范围生成器,能对输入流调用>>来生成动态的范围,好处之一是避免了手动构造哨兵
1 2 3 4 5 6 7 8 9 #include <ranges> #include <iostream> int main () { auto t = std::ranges::istream_view <int >(std::cin); for (auto x : std::ranges::transform_view (t, [](auto z) { return z * z;})) { std::cout << x << '\n' ; } }