boost :: iostreams压缩的字符串长度

时间:2012-10-22 03:41:50

标签: c++ boost-iostreams

我有一个字符串(有一些固定长度),我需要压缩然后比较压缩长度(作为数据冗余的代理或作为Kolmogorov复杂度的粗略近似)。目前,我正在使用boost :: iostreams进行压缩,这似乎运行良好。但是,我不知道如何获取压缩数据的大小。有人可以帮忙吗?

代码段是

#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/filesystem.hpp>
#include <string>
#include <sstream>

namespace io = boost::iostreams;

int main() {

  std::string memblock;

  std::cout << "Input the string to be compressed:";
  std::cin >> memblock;

  std::cout << memblock << std::endl;

  io::filtering_ostream out;
  out.push(io::gzip_compressor());
  out.push(io::file_descriptor_sink("test.gz"));
  out.write (memblock.c_str(), memblock.size());

  std::cout << out.size() << std::endl;

  return 0;

}

3 个答案:

答案 0 :(得分:5)

您可以尝试在压缩器和接收器之间添加boost::iostreams::counter链接,然后调用它的characters()成员来获取通过它的字节数。

这对我有用:

#include <boost/iostreams/filter/counter.hpp>

...

io::filtering_ostream out;
out.push(io::counter());
out.push(io::gzip_compressor());
out.push(io::counter());
out.push(io::file_descriptor_sink("test.gz"));
out.write (memblock.c_str(), memblock.size());
io::close(out); // Needed for flushing the data from compressor

std::cout << "Wrote " << out.component<io::counter>(0)->characters() << " bytes to compressor, "
    << "got " << out.component<io::counter>(2)->characters() << " bytes out of it." << std::endl;

答案 1 :(得分:1)

我想出了另一种(并且稍微有点滑动)的方法来实现字符串的压缩长度。我想在这里分享它,但基本上它只是将未压缩的字符串传递给过滤的缓冲区并将输出复制回字符串:

template<typename T>
inline std::string compressIt(std::vector<T> s){

    std::stringstream uncompressed, compressed;
    for (typename std::vector<T>::iterator it = s.begin();
         it != s.end(); it++)
        uncompressed << *it;

    io::filtering_streambuf<io::input> o;
    o.push(io::gzip_compressor());
    o.push(uncompressed);
    io::copy(o, compressed);

    return compressed.str();
}

稍后可以轻松地将压缩字符串的大小设为

compressIt(uncompressedString).size()

我觉得最好不要像以前那样创建输出文件。

欢呼声, NIKHIL

答案 2 :(得分:0)

另一种方式是

stream<array_source> input_stream(input_data,input_data_ize);
stream<array_sink> compressed_stream(compressed_data,alloc_compressed_size);  
filtering_istreambuf out;
out.push(gzip_compressor());
out.push(input_stream);
int compressed_size = copy(out,compressed_stream);
cout << "size of compressed_stream" << compressed_size << endl;