On May 24, 2:03*pm, "Thomas J. Gritzan" <phygon_antis...@gmx.de>
wrote:
> Am 24.05.2011 13:51, schrieb mathieu:
>
>
>
>
>
> > On May 24, 1:01 pm, Michael Doubez<michael.dou...@free.fr> *wrote:
> >> On 24 mai, 11:16, gwowen<gwo...@gmail.com> *wrote:
>
> >>> On May 24, 9:58 am, mathieu<mathieu.malate...@gmail.com> *wrote:
>
> >>>> Dear all,
>
> >>>> * *I do not understand how to use the STL vector class with the
> >>>> ifstream class. I would like to reserve a chunk of memory (no
> >>>> initialization is required) and fill it with values from a file. As
> >>>> far as I understand vector::reserve requires a subsequent call to
> >>>> push_back or insert. However I do not see how I can do this in the
> >>>> following example:
>
> >>>> #include<fstream>
> >>>> #include<vector>
>
> >>>> int main(int argc, char *argv[])
> >>>> {
> >>>> * *const char *filename = argv[1];
> >>>> * *std::ifstream is( filename );
> >>>> * *const size_t l = 512;
> >>>> * *std::vector<char> *v;
> >>>> * *v.reserve( l ); // need push_back or insert
>
> >>> If you reserve() space, you can't read or write to that space until
> >>> you also adjust the size (as push_back() will, or resize()). *The
> >>> reserve() may well speed your code up.
>
> >>> char tmp;
> >>> is.read(&tmp,1);
> >>> v.push_back(tmp);
>
> >>> // the C++/STL like solution will use an istream_iterator and a
> >>> back_inserter
> >>> // I've got to say, I don't care for it...
> >>> vector<char> *V;
> >>> copy(istream_iterator<char>(is), istream_iterator<char>(),
> >>> back_inserter(V));
>
> >> Or simply:
> >> v.assign(stream_iterator<char>(is), istream_iterator<char>());
>
> > It does not work for me. istream_iterator does not implement +()
> > operator:
>
> > * *v.assign( std::istream_iterator<char>(is),
> > std::istream_iterator<char>(is)+l);
>
> You are not supposed to do +x on this.
>
> istream_iterator<char>(is) is an iterator refering to the begin of the
> stream while istream_iterator<char>() refers to the end of the stream,
> just like c.begin() and c.end() for any container.
> That pair of iterators reads from the stream until it hits the end of
> the stream (like end of file).
>
> If you want to read into a fixed buffer of std::vector:
>
> std::ifstream is( filename );
> const size_t size = 512;
> std::vector<char> buffer(size);
As said in my original post, I do not want to initialize the vector,
simply because this should not be required.
Thanks
|