Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inputstream to vector<char> - vector iterator not dereferencable

first of all, I'm new to C++, coming from Java. I want to do a simple thing: load a picture from the web using the URDL-libs and save it to a char-vector. Loading the image works fine, I'm able to save it to the disk, but when I try to load it into a char-vector instead, I get this error at runtime:

Expression: vector iterator not dereferencable

this is my code:

urdl::istream inputStream( url );
if( inputStream )
{
    inputStream >> std::noskipws;
    istream_iterator<char> inputStreamIterator( inputStream ), inputStreamEnd;
    string dateiname = "test.png";
    vector<char> imageVector;

    ofstream outputStream( dateiname, ios_base::binary );
    ostream_iterator<char> outputStreamIterator(outputStream);
    copy( inputStreamIterator, inputStreamEnd,  imageVector.begin());
}
like image 237
Mirco Avatar asked Dec 06 '25 17:12

Mirco


2 Answers

Your std::vector<char> has no capacity and you can't use std::copy directly. Instead, you should use std::back_insert_iterator that will call push_back() on your std::vector. The easiest way to build such an iterator is to use the std::back_inserter template function.

std::copy(inputStreamIterator, inputStreamEnd,
    std::back_inserter(imageVector));
like image 152
Sylvain Defresne Avatar answered Dec 08 '25 11:12

Sylvain Defresne


You can avoid the std::copy call altogether, by initializing the vector with your input iterators:

std::vector<char> imageVector(
    std::istream_iterator<char>(inputStream), 
    std::istream_iterator<char>());

or

std::vector<char> imageVector(
    std::istreambuf_iterator<char>(inputStream),
    std::istreambuf_iterator<char>());
like image 20
Robᵩ Avatar answered Dec 08 '25 09:12

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!