Range-based loop over an input stream

前端 未结 4 1069
醉梦人生
醉梦人生 2021-02-08 16:57

To iterate over an input stream, we would usually use a std::istream_iterator like so:

typedef std::istream_iterator input_iterato         


        
4条回答
  •  一个人的身影
    2021-02-08 17:40

    An obvious approach is to use a simple decorator for your stream providing the type and the necessary interface. Here is how this could look like:

    template 
    struct irange
    {
        irange(std::istream& in): d_in(in) {}
        std::istream& d_in;
    };
    template 
    std::istream_iterator begin(irange r) {
        return std::istream_iterator(r.d_in);
    }
    template 
    std::istream_iterator end(irange) {
        return std::istream_iterator();
    }
    
    for (auto const& x: irange(std::ifstream("file") >> std::skipws)) {
        ...
    }
    

提交回复
热议问题