您好,登錄后才能下訂單哦!
在C++中,有多種高效的方法可以用于解壓縮數據
std::istream
和std::ostream
進行解壓縮:#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <zlib.h>
std::vector<char> decompress(const std::vector<char>& compressedData) {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.avail_in = compressedData.size();
zs.next_in = reinterpret_cast<Bytef*>(compressedData.data());
std::vector<char> decompressedData;
char buffer[32768];
do {
zs.avail_out = sizeof(buffer);
zs.next_out = reinterpret_cast<Bytef*>(buffer);
int ret = inflate(&zs, Z_NO_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
throw std::runtime_error("Decompression failed");
}
size_t have = sizeof(buffer) - zs.avail_out;
decompressedData.insert(decompressedData.end(), buffer, buffer + have);
} while (zs.avail_out == 0);
inflateEnd(&zs);
return decompressedData;
}
zlib
進行解壓縮:首先,需要安裝zlib
庫并將其包含在項目中。然后,可以使用以下代碼進行解壓縮:
#include <iostream>
#include <fstream>
#include <vector>
#include <zlib.h>
std::vector<char> decompress(const std::vector<char>& compressedData) {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.avail_in = compressedData.size();
zs.next_in = reinterpret_cast<Bytef*>(compressedData.data());
std::vector<char> decompressedData;
char buffer[32768];
do {
zs.avail_out = sizeof(buffer);
zs.next_out = reinterpret_cast<Bytef*>(buffer);
int ret = inflate(&zs, Z_NO_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
throw std::runtime_error("Decompression failed");
}
size_t have = sizeof(buffer) - zs.avail_out;
decompressedData.insert(decompressedData.end(), buffer, buffer + have);
} while (zs.avail_out == 0);
inflateEnd(&zs);
return decompressedData;
}
boost.iostreams
進行解壓縮:首先,需要安裝boost
庫并將其包含在項目中。然后,可以使用以下代碼進行解壓縮:
#include <iostream>
#include <fstream>
#include <vector>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
std::vector<char> decompress(const std::vector<char>& compressedData) {
std::vector<char> decompressedData;
boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
in.push(boost::iostreams::gzip_decompressor());
in.push(boost::iostreams::input(compressedData.data(), compressedData.size()));
boost::iostreams::copy(in, std::back_inserter(decompressedData));
return decompressedData;
}
這些方法都可以用于解壓縮數據,具體選擇哪種方法取決于你的需求和項目結構。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。