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());
}
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));
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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With