用qt写利用哈夫曼压缩与解压缩文件的C++代码

时间: 2024-02-15 11:02:00 浏览: 22
以下是使用 Qt 编写的哈夫曼压缩与解压缩文件的 C++ 代码示例: ```cpp #include <iostream> #include <queue> #include <unordered_map> #include <fstream> #include <bitset> #include <QFile> using namespace std; // 定义哈夫曼树节点 struct Node { char ch; int freq; Node* left; Node* right; Node(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {} Node(int f) : freq(f), left(nullptr), right(nullptr) {} ~Node() { delete left; delete right; } }; // 定义哈夫曼树节点比较函数 struct NodeCompare { bool operator()(Node* a, Node* b) { return a->freq > b->freq; } }; // 构建哈夫曼树 Node* buildHuffmanTree(const unordered_map<char, int>& freqMap) { priority_queue<Node*, vector<Node*>, NodeCompare> pq; for (auto& pair : freqMap) { pq.push(new Node(pair.first, pair.second)); } while (pq.size() > 1) { Node* left = pq.top(); pq.pop(); Node* right = pq.top(); pq.pop(); Node* parent = new Node(left->freq + right->freq); parent->left = left; parent->right = right; pq.push(parent); } return pq.top(); } // 构建哈夫曼编码表 void buildHuffmanCodeTable(Node* root, string code, unordered_map<char, string>& codeTable) { if (!root) { return; } if (root->ch != '\0') { codeTable[root->ch] = code; } buildHuffmanCodeTable(root->left, code + "0", codeTable); buildHuffmanCodeTable(root->right, code + "1", codeTable); } // 压缩文件 void compressFile(const string& inputFile, const string& outputFile) { // 统计每个字符出现的次数 unordered_map<char, int> freqMap; ifstream in(inputFile, ios_base::binary); char ch; while (in.get(ch)) { freqMap[ch]++; } in.close(); // 构建哈夫曼树和编码表 Node* root = buildHuffmanTree(freqMap); unordered_map<char, string> codeTable; buildHuffmanCodeTable(root, "", codeTable); // 将编码表写入压缩文件 QFile out(outputFile.c_str()); if (out.open(QIODevice::WriteOnly | QIODevice::Truncate)) { for (auto& pair : codeTable) { out.write(pair.first); out.write(pair.second.c_str(), pair.second.size()); out.write("\n"); } } out.close(); // 写入压缩后的数据 bitset<8> bits; int bitCount = 0; in.open(inputFile, ios_base::binary); out.open(outputFile.c_str(), QIODevice::Append); while (in.get(ch)) { string code = codeTable[ch]; for (char c : code) { bits[bitCount++] = (c == '1'); if (bitCount == 8) { char byte = static_cast<char>(bits.to_ulong()); out.write(&byte, 1); bitCount = 0; } } } if (bitCount > 0) { char byte = static_cast<char>(bits.to_ulong()); out.write(&byte, 1); } in.close(); out.close(); // 释放哈夫曼树的内存 delete root; } // 解压缩文件 void decompressFile(const string& inputFile, const string& outputFile) { // 读取编码表 unordered_map<string, char> codeTable; ifstream in(inputFile, ios_base::binary); char ch; string code; while (in.get(ch)) { if (ch == '\n') { codeTable[code] = ch; code.clear(); } else { code += ch; } } in.close(); // 解压缩文件 bitset<8> bits; int bitCount = 0; in.open(inputFile, ios_base::binary); in.seekg(in.tellg() - static_cast<streamoff>(codeTable.size() * 2 + 1)); QFile out(outputFile.c_str()); if (out.open(QIODevice::WriteOnly | QIODevice::Truncate)) { Node* root = nullptr; while (in.read(&ch, 1)) { bits = bitset<8>(ch); for (int i = 0; i < 8 && (root || i < bitCount); i++) { bool bit = bits[i]; if (!root) { root = new Node(0); } root = (bit ? root->right : root->left); if (root->ch != '\0') { out.write(&root->ch, 1); root = nullptr; } } bitCount = (bitCount + 8) % 8; } delete root; } in.close(); out.close(); } int main() { string inputFile = "input.txt"; string compressedFile = "compressed.bin"; string decompressedFile = "output.txt"; compressFile(inputFile, compressedFile); decompressFile(compressedFile, decompressedFile); return 0; } ``` 在这个示例中,我们首先定义了一个 `Node` 结构体来表示哈夫曼树的节点,其中 `ch` 表示节点代表的字符,`freq` 表示该字符出现的次数,`left` 和 `right` 分别表示左右子节点。然后,我们定义了一个 `NodeCompare` 结构体来比较两个节点的大小,以便在构建哈夫曼树时使用优先队列来实现最小堆。接着,我们实现了 `buildHuffmanTree` 函数来构建哈夫曼树,使用了一个哈希表来统计每个字符出现的次数,并且使用优先队列来不断合并出现次数最小的两个节点,直到只剩下一个根节点。然后,我们实现了 `buildHuffmanCodeTable` 函数来构建哈夫曼编码表,使用了递归的方式来遍历哈夫曼树,并且将每个字符对应的编码保存在哈希表中。接着,我们实现了 `compressFile` 函数来压缩文件,首先调用 `buildHuffmanTree` 和 `buildHuffmanCodeTable` 函数来构建哈夫曼树和编码表,然后将编码表写入压缩文件,并且使用位运算和 `bitset` 来将每个字符压缩成其对应的编码。最后,我们实现了 `decompressFile` 函数来解压缩文件,首先读取编码表,然后使用位运算和 `bitset` 来将每个编码解压缩成原始字符,并且将解压缩后的字符写入输出文件中。

相关推荐

最新推荐

recommend-type

运用哈夫曼编码压缩解压文件源代码

运用哈夫曼编码压缩解压文件源代码,代码有详细的注释,很好的压缩解压的源代码
recommend-type

哈夫曼编码压缩解压缩程序(CPP写的)

哈夫曼编码压缩解压缩程序(CPP写的) 多媒体课程设计中也许能用的到 希望能帮到能用的到的人
recommend-type

C++实现哈夫曼树简单创建与遍历的方法

主要介绍了C++实现哈夫曼树简单创建与遍历的方法,对于C++算法的学习来说不失为一个很好的借鉴实例,需要的朋友可以参考下
recommend-type

数据结构课程设计-基于Huffman编码的文件压缩与解压缩.docx

数据结构课程设计-基于Huffman编码的文件压缩与解压缩 2.2.1结构设计 typedef struct Node { unsigned char ch;//字符 double weight;//字符的频数 int parent,lchild,rchild; }HTNode,HuffmanTree[2*N-1];//...
recommend-type

Java swing + socket + mysql 五子棋网络对战游戏FiveChess.zip

五子棋游戏想必大家都非常熟悉,游戏规则十分简单。游戏开始后,玩家在游戏设置中选择人机对战,则系统执黑棋,玩家自己执白棋。双方轮流下一棋,先将横、竖或斜线的5个或5个以上同色棋子连成不间断的一排者为胜。 【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。 【技术】 Java、Python、Node.js、Spring Boot、Django、Express、MySQL、PostgreSQL、MongoDB、React、Angular、Vue、Bootstrap、Material-UI、Redis、Docker、Kubernetes
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

用matlab绘制高斯色噪声情况下的频率估计CRLB,其中w(n)是零均值高斯色噪声,w(n)=0.8*w(n-1)+e(n),e(n)服从零均值方差为se的高斯分布

以下是用matlab绘制高斯色噪声情况下频率估计CRLB的代码: ```matlab % 参数设置 N = 100; % 信号长度 se = 0.5; % 噪声方差 w = zeros(N,1); % 高斯色噪声 w(1) = randn(1)*sqrt(se); for n = 2:N w(n) = 0.8*w(n-1) + randn(1)*sqrt(se); end % 计算频率估计CRLB fs = 1; % 采样频率 df = 0.01; % 频率分辨率 f = 0:df:fs/2; % 频率范围 M = length(f); CRLB = zeros(M,1); for
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。