你如何压缩数据并将其放入向量中?

How do you Deflate data and put it into a vector?

使用 zstr, a header-only C++ zlib wrapper library,我正在尝试 Deflate a std::string 并将其放入 std::vector<unsigned char>.

zstr::ostream deflating_stream(std::cout);
deflating_stream.write(content.data(), content.size());

上面的代码有效:它打印了 Deflate'd。问题是,我不熟悉 C++ 流,我无法将其放入 std::vector。用 std::ostringstreamstd::ostreamstd::istringstreamstd::istreambuf_iteratorstd::streambuf.rdbuf() 等尝试了几次,但唯一的方法是出来的是空虚输出(.tellp() == 0).

我如何缩小一个std::string并将其放入std::vector<unsigned char>


以下是我的一些尝试。我不知道如何访问 Deflate 的数据。

std::istringstream is;
std::ostream ss(is.rdbuf());
zstr::ostream deflating_stream(ss);
deflating_stream.write(
    uncompressed_string.data(),
    uncompressed_string.size()
);
the_vector.insert(
    the_vector.cend(),
    std::istreambuf_iterator<char>(is),
    std::istreambuf_iterator<char>()
);
std::ostringstream oss;
zstr::ostream deflating_stream(oss);
deflating_stream.write(
    uncompressed_string.data(),
    uncompressed_string.size()
);
const std::string deflated = oss.str();
the_vector.insert(
    the_vector.cend(),
    deflated.cbegin(),
    deflated.cend()
);
std::stringstream ss;
zstr::ostream deflating_stream(ss);
deflating_stream.write(
    uncompressed_string.data(),
    uncompressed_string.size()
);
std::string deflated = ss.str();
std::cout << deflated.size(); // Says 0.

像这样的东西有效:

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>

#include "zstr.hpp"

int main() {
  std::string text{"some text\n"};
  std::stringbuf buffer;
  zstr::ostream compressor{&buffer};

  // Must flush to get complete gzip data in buffer
  compressor << text << std::flush;

  // It's probably easier to use just the string...
  auto compstr = buffer.str();
  std::vector<unsigned char> deflated;
  deflated.resize(compstr.size());
  std::copy(compstr.begin(), compstr.end(), deflated.begin());

  std::cout.write(reinterpret_cast<char *>(deflated.data()), deflated.size());
  return 0;
}

编译后:

$ ./a.out | zcat
some text