方便地将std :: vector <unsigned char =“”>复制到输入流(std :: istream)对象</unsigned>

时间:2012-02-20 08:47:17

标签: c++ vector copy istream unsigned-char

我正在尝试使用第三方库中的函数,并期望输入流对象,其中传输二进制文件数据。

签名看起来像这样:

doSomething(const std::string& ...,
          const std::string& ...,
          std::istream& aData,
          const std::string& ...,
          const std::map<std::string, std::string>* ...,
          long ...,
          bool ...);

由于我无法更改/更改此第三方库/功能,因此我必须适应“我的”代码。在调用的地方,我有一个std :: vector,它包含了预期在istream对象中传递的数据。目前,我将矢量复制到流中,通过迭代并使用&lt;&lt;运算符逐字节复制。

我强烈怀疑可能有一种更有效/方便的方式但到目前为止找不到任何有用的东西。非常感谢任何帮助/您的想法。

最佳, JR

2 个答案:

答案 0 :(得分:15)

您可以使用vector个字符作为输入流的基础缓冲区,而无需复制向量的内容:

std::vector<unsigned char> my_vec;
my_vec.push_back('a');
my_vec.push_back('b');
my_vec.push_back('c');
my_vec.push_back('\n');

// make an imput stream from my_vec
std::stringstream is;
is.rdbuf()->pubsetbuf(reinterpret_cast<char*>(&my_vec[0]), my_vec.size());

// dump the input stream into stdout
std::cout << is.rdbuf();

@NeilKirk报告the above method of using pubsetbuf is non-portable

一种可移植的方法是使用boost::iostreams库。这是如何从向量构造输入流而不复制其内容:

#include <iostream>
#include <vector>

#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>

int main() {
    std::vector<unsigned char> my_vec;
    my_vec.push_back('a');
    my_vec.push_back('b');
    my_vec.push_back('c');
    my_vec.push_back('\n');

    // Construct an input stream from the vector.
    boost::iostreams::array_source my_vec_source(reinterpret_cast<char*>(&my_vec[0]), my_vec.size());
    boost::iostreams::stream<boost::iostreams::array_source> is(my_vec_source);

    // Dump the input stream into stdout.
    std::cout << is.rdbuf();
}

答案 1 :(得分:7)

vector<unsigned char> values;
// ...

stringstream ioss;    
copy(values.begin(), values.end(),
     ostream_iterator<unsigned char>(ioss,","));

// doSomething(a, b, ioss, d, e, f, g);