2

我有一个字符串(一些固定长度),我需要对其进行压缩,然后比较压缩后的长度(作为数据冗余的代理或作为 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;

}
4

3 回答 3

6

您可以尝试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;
于 2012-10-22T05:13:42.163 回答
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()

我觉得这更好,因为它不需要我像以前那样创建输出文件。

干杯,尼基尔

于 2012-10-27T09:32:10.063 回答
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;
于 2016-02-01T21:07:12.563 回答