c++ - 我无法理解 std::istream_iterator 的使用

标签 c++ boost iterator istream-iterator

我看不懂下面的代码。

(来自 https://www.boost.org/doc/libs/1_74_0/more/getting_started/unix-variants.html)

#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    using namespace boost::lambda;
    typedef std::istream_iterator<int> in;

    std::for_each(
        in(std::cin), in(), std::cout << (_1 * 3) << " " );
}

网页没有对代码做任何解释。

我无法理解的是带有 std::for_each 函数的那一行。

std::for_each 定义如下。

template <class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function fn);

所以firstin(std::cin)last只是in()functioncout 语句。

谁能给我解释一下示例代码中firstlast的语法和含义?

first迭代器貌似是用初值std::cin构造的,但是in()对last有什么用值(value)?

我也无法理解 _1 部分。

程序输出 3 * 我输入的任意数量的整数值。

最佳答案

首先解释一下 std::for_each 功能。

该函数从头到尾遍历一组迭代器,为范围内的每个元素调用一个函数。

如果你有整数 vector :

std::vector<int> v = { 1, 2, 3, 4 };

并且想要打印它们,那么你可以这样做:

std::for_each(v.begin(), v.end(), [](int val) { std::cout << val; });

上面调用std::for_each相当于:

for (auto i = v.begin(); i != v.end(); ++i)
{
    std::cout << *i;
}

现在,如果我们去使用 std::istream_iterator 在问题中,它包装了输入运算符 >>使用迭代器。

重写 std::for_each使用标准 C++ lambda 调用,它看起来像这样:

std::for_each(in(std::cin), in(), [](int value) { std::cout << (value * 3) << " " ); });

如果我们把它翻译成“正常”for迭代器循环然后它变成:

for (auto i = in(std::cin); i != in(); ++i)
{
    std::cout << (*i * 3) << " ";
}

它的作用是从 std::cin 读取整数输入(直到文件结束或错误) , 然后输出值乘以 3和一个空格。


如果您想知道 in(std::cin)in() , 你必须记住 in是类型 std::istream_iterator<int> 的别名.

这意味着 in(std::cin)std::istream_iterator<int>(std::cin)相同. IE。它创建了一个 std::istream_iterator<int>对象,并传递 std::cin给构造函数。和 in()构造一个结束迭代器对象。

更清楚的是,代码等同于:

std::istream_iterator<int> the_beginning(std::cin);
std::istream_iterator<int> the_end;  // Default construct, becomes the "end" iterator

for (std::istream_iterator<int> i = the_beginning; i != the_end; ++i)
{
    int value = *i;  // Dereference iterator to get its value
                     // (effectively the same as std::cin >> value)

    std::cout << (value * 3) << " ";
}

关于c++ - 我无法理解 std::istream_iterator 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63789443/

相关文章:

c++ - 在 C++ 中访问 lambda 之外的 lambda 捕获初始化变量

c++ - 在没有连接的套接字中写入时没有错误

python - 来自迭代器的随机项目?

java - Scala HashMap 抛出键未找到异常

c++ - 如果我还使用复制构造函数和重载=运算符,是否需要析构函数?

c++ - 如何在 vscode 中链接并包含来自不同目录的 C++ header

C++ ExportAsFixedFormat 保存为 PDF

c++ - 如何在 C++ 中对派生类使用 Boost 序列化?

c++ - Perl正则表达式中 "~"标记有什么用?

python - 联合异步迭代器会发生什么?