Nik*_*shi 2 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;
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试boost::iostreams::counter在压缩器和接收器之间添加链接,然后调用它的characters()成员以获取通过它的字节数.
这对我有用:
#include <boost/iostreams/filter/counter.hpp>
Run Code Online (Sandbox Code Playgroud)
...
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;
Run Code Online (Sandbox Code Playgroud)