代码之家  ›  专栏  ›  技术社区  ›  nakiya

如何创建将从输入流中读取下一个值的函子?

  •  0
  • nakiya  · 技术社区  · 14 年前

    像这样的:

    std::bind1st(std::mem_fun(&istream::get ??), cin) . 这似乎对我不起作用。

    编辑:

    使用:

    vector<int> vNumbers;
    generate_n(back_inserter(vNumbers), iNumCount, functor);
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   Marcelo Cantos    14 年前

    我不认为标准绑定函数允许您定义空函数。 bind1st 绑定到 二元的 函数并返回一元函数,该函数将其参数作为绑定函数的第二个参数传递。

    但是,您可以走出标准库,使用Boost.Bind:

    boost::bind(&istream::get, &cin)
    
        2
  •  1
  •   Alexandre C.    14 年前

    std::mem_fun 拿一个指针。我也是

    bind(std::mem_fun(&istream::get), &cin)
    

    哪里

    template <typename F, typename Res, typename Arg>
    struct binder
    {
        binder(F const& f, Arg const& arg) : f(f), arg(arg) {}
        Res operator()() { return f(arg); }
    private:
        F f; Arg arg;
    };
    
    template <typename F, typename Arg>
    binder<F, typename F::result_type, Arg> bind(F const& f, Arg const& arg)
    { return binder<F, typename F::result_type, Arg>(f, arg); }
    

    您也可以使用 std::istream_iterator 海关/被盗 copy_n 算法(可惜不是标准的):

    template <typename I, typename O>
    O copy_n(size_t n, I first, I last, O result)
    {
        size_t k = 0;
        while (first != last && k++ < n) *result++ = *first++;
        return result;
    }