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

后端 未结 8 757
情深已故
情深已故 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:41

    Looking into this a bit I don't think reading directly into a set will work, as you need to call insert on it to actually add the elements (I could be mistaken, it is rather early in the morning here). Though looking at the STL documentation in VS2005 briefly I think something using the generate_n function should work, for instance:

    std::istream ins;
    std::set my_set;
    std::vector my_vec;
    
    struct read_functor
    {
        read_functor(std::istream& stream) :
            m_stream(stream)
        {
        }
    
        int operator()
        {
            int temp;
            m_stream >> temp;
            return temp;
        }
    private:
        std::istream& m_stream;
    };
    
    std::set::size_type size;
    ins >> size;
    my_vec.reserve(size);
    
    std::generate_n(my_vec.begin(), size, read_functor(ins));
    my_set.insert(my_vec.begin(), my_vec.end());
    

    Hopefully that's either solved your problem, or convinced you that the loop isn't that bad in the grand scheme of things.

提交回复
热议问题