How to read arbitrary number of values using std::copy?

后端 未结 8 695
情深已故
情深已故 2021-01-05 02:24

I\'m trying to code opposite action to this:

std::ostream outs; // properly initialized of course
std::set my_set; // ditto

outs << my_set.         


        
8条回答
  •  借酒劲吻你
    2021-01-05 02:51

    You could derive from the istream_iterator.
    Though using Daemin generator method is another option, though I would generate directly into the set rather than use an intermediate vector.

    #include 
    #include 
    #include 
    #include 
    
    
    template
    struct CountIter: public std::istream_iterator
    {
        CountIter(size_t c)
            :std::istream_iterator()
            ,count(c)
        {}
        CountIter(std::istream& str)
            :std::istream_iterator(str)
            ,count(0)
        {}
    
        bool operator!=(CountIter const& rhs) const
        {
            return (count != rhs.count) && (dynamic_cast const&>(*this) != rhs);
        }
        T operator*()
        {
            ++count;
            return std::istream_iterator::operator*();
        }
    
        private:
            size_t  count;
    };
    
    int main()
    {
        std::set       x;
    
        //std::copy(std::istream_iterator(std::cin),std::istream_iterator(),std::inserter(x,x.end()));
        std::copy(
                    CountIter(std::cin),
                    CountIter(5),
                    std::inserter(x,x.end())
                );
    }
    

提交回复
热议问题