8

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

签名看起来像这样:

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

Since I can't alter/change this 3rd party lib/function, I have to adapt in "my" code. In the calling place, I have a std::vector which contains the data which is expected to be passed in an istream object. Currently I copy the vector to the stream, by iterating over it and using the << operator to copy byte by byte.

I strongly suspect that there might be a more effective/convenient way but couldn't find anything useful up to now. Any help/your thoughts are greatly appreciated.

Best, JR

4

2 回答 2

16

您可以使用 a vectorof characters 作为输入流的底层缓冲区,而无需复制向量的内容:

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 报告说上述使用方法pubsetbuf是 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();
}
于 2012-02-20T08:59:29.777 回答
8
vector<unsigned char> values;
// ...

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

// doSomething(a, b, ioss, d, e, f, g);
于 2012-02-20T08:59:08.857 回答