Cant create vector from istream_iterator

D

DeveloperDave

Hi,
I am having trouble constructing a vector using some istream_iterators
and a file.....

I have written some code that opens a file and creates a few
istream_iterators.
i.e.

std::fstream file(filename.c_str(), (ios_base::in |
ios_base::binary));
istream_iterator<unsigned char>pos = istream_iterator<unsigned
char>(file);
istream_iterator<unsigned char>start = pos;
istream_iterator<unsigned char>end;

I increment the 'pos' iterator, to iterate through the file. At a
certian point I update 'end' to be equal to 'pos'.
I can print out the values that 'start' and 'end' both reference and
see they are the bytes from the file that I would expect, but when I
try to create a vector, it is always empty e.g.

vector<unsigned char>myVector(start, end);

myVector.size() always returns 0.

Am I using the istream_iterator in the wrong way?

Thanks
 
B

Bo Persson

DeveloperDave said:
Hi,
I am having trouble constructing a vector using some
istream_iterators and a file.....

I have written some code that opens a file and creates a few
istream_iterators.
i.e.

std::fstream file(filename.c_str(), (ios_base::in |
ios_base::binary));
istream_iterator<unsigned char>pos = istream_iterator<unsigned
char>(file);
istream_iterator<unsigned char>start = pos;
istream_iterator<unsigned char>end;

I increment the 'pos' iterator, to iterate through the file. At a
certian point I update 'end' to be equal to 'pos'.
I can print out the values that 'start' and 'end' both reference and
see they are the bytes from the file that I would expect, but when I
try to create a vector, it is always empty e.g.

vector<unsigned char>myVector(start, end);

myVector.size() always returns 0.

Am I using the istream_iterator in the wrong way?

Yes. :)

The istream_iterator is an input iterator, which only has to support a
single pass through the sequence.

To do what you attempt requires a forward iterator, which would allow
you to do mutliple paees over the sequence.

http://www.sgi.com/tech/stl/Iterators.html


In your particular case, perhaps you can push_back each character
during your first (and only!) pass?



Bo Persson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top