2012-10-22 6 views
2

문자열을 압축하고 압축 된 길이를 비교해야합니다 (데이터의 중복성을위한 프록시 또는 대략적인 근사값으로 사용). Kolmogorov 복잡성). 현재 압축을 위해 boost :: iostreams를 사용하고 있습니다. 그러나 압축 된 데이터의 크기를 얻는 방법을 모르겠습니다. 누군가가 도와 줄 수 있니?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; 

} 
+1

것입니까? 그렇다면 결과를 문자열로 얻고 그 길이를 얻는 것은 간단합니다. –

답변

4

당신은 당신이 압축기 사이에 체인 침몰하고 그것을 통해 갔다 바이트 수를 얻을 수 characters() 회원의 부르심에 boost::iostreams::counter를 추가하는 시도 할 수있다.

이 나를 위해 작동합니다

#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; 
+0

감사합니다. 잘 작동한다 :) –

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

0

다른 하나의 방법은 당신이 이제 stringstream 같은 객체에 데이터를 쓸 수

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;