如何将`std::vector<uchar>`保存到`std::ostream`中? [英] How to save `std::vector<uchar>` into `std::ostream`?
问题描述
我们已经用<a href="http://opencv.willowgarage.com/documentation/cpp/reading_and_writing_images_and_video.html" rel="创建并填充了一些std::vector<uchar>
noreferrer">openCV imencode
例如.现在我们想将它流式传输到一些 http_lib 中,它可以采用某种 ostream(ostringstream) 例如,或者我们只是想在我们使用 ofstream 调试我们的程序时保存.所以我想知道如何将 std::vector
放入 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
?
推荐答案
使用 write
:
void send_data(std::ostream & o, const std::vector<uchar> & v)
{
o.write(reinterpret_cast<const char*>(v.data()), v.size());
}
ostream 需要裸 char
s,但是通过转换该指针将 uchar 视为那些很好.在较旧的编译器上,您可能不得不说 &v[0]
而不是 v.data()
.
The ostream expects naked char
s, 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()
.
如果您喜欢一些错误检查,您可以将 write()
的结果作为另一个 std::ostream&
或作为 bool
返回设施.
You can return the result of write()
as another std::ostream&
or as a bool
if you like some error checking facilities.
这篇关于如何将`std::vector<uchar>`保存到`std::ostream`中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!