Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 938
Rella Avatar asked Nov 15 '11 21:11

Rella


2 Answers

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.

like image 195
Kerrek SB Avatar answered Oct 15 '22 08:10

Kerrek SB


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,"") );
like image 31
John Dibling Avatar answered Oct 15 '22 09:10

John Dibling