How to save `std::vector<uchar>` into `std::ostream`?
Asked Answered
B

2

6

We have created and filled some std::vector<uchar> with openCV imencode for example. Now we want to stream it for example into some http_lib which can take some sort of ostream (ostringstream) for example, or we just want to save in while we debug our programm with ofstream. So I wonder how to put std::vector<uchar> into std::ostream?

Brioche answered 15/11, 2011 at 21:2 Comment(1)
Probably by iterating the elements and streaming each one in individually.Lodmilla
F
11

Use write:

void send_data(std::ostream & o, const std::vector<uchar> & v)
{
  o.write(reinterpret_cast<const char*>(v.data()), v.size());
}

The ostream expects naked chars, but it's fine to treat uchars as those by casting that pointer. On older compilers you may have to say &v[0] instead of v.data().

You can return the result of write() as another std::ostream& or as a bool if you like some error checking facilities.

Fredi answered 15/11, 2011 at 21:3 Comment(2)
+10 For taking the probable chance of a non-C++11 compiler into account. And +1 for the actual answer, of course.Tommie
@ChristianRau: I take it that was a binary +10 :-)Fredi
U
1

Depending on how you want the output formatted, you might be able to use copy in conjunction with ostream_iterator:

#include <iterator>

/*...*/

copy( v.begin(), v.end(), ostream_iterator<uchar>(my_stream,"") );
Unmeriting answered 15/11, 2011 at 21:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.