【问题标题】:Conveniently copy std::vector<unsigned char> to input stream (std::istream) object方便地将 std::vector<unsigned char> 复制到输入流 (std::istream) 对象
【发布时间】:2012-03-10 14:58:28
【问题描述】:

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

签名是这样的:

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

由于我无法更改/更改此第 3 方库/函数,因此我必须在“我的”代码中进行调整。在调用位置,我有一个 std::vector ,其中包含预期将在 istream 对象中传递的数据。目前我将向量复制到流中,通过迭代它并使用

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

最好, JR

【问题讨论】:

  • 我不明白您希望如何写入input 流。
  • 是的,您如何在 istream 上使用
  • @BillyONEal 他可能在使用 iostream?它继承自 istream 和 ostream。
  • 不,等一下,我对 IntelliSense 太信任了。由于显而易见的原因,它没有编译:)....

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


【解决方案1】:

您可以使用 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();
}

【讨论】:

  • 指向向量数据的指针很容易失效。然而,字符串流的临时性使其相当安全。考虑到这一点,这是一个很好的答案。
  • 这不保证能正常工作,而且在 VS2015 上也不能
【解决方案2】:
vector<unsigned char> values;
// ...

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

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

【讨论】:

  • 感谢您为我指明正确的方向! `stringstream ss;复制(values.begin(), values.end(), ostream_iterator(ss,""));'完美运行!
猜你喜欢
  • 2012-03-07
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多