gpt4 book ai didi

c++ - 通过 boost::iostreams 压缩字符串的长度

转载 作者:搜寻专家 更新时间:2023-10-31 00:17:36 26 4
gpt4 key购买 nike

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

}

最佳答案

您可以尝试将 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;

关于c++ - 通过 boost::iostreams 压缩字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13004706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com