Algorithm第四版算法 C++实现(二十八)——游程编码(二进制文件压缩机制)

游程编码的原理很简单,他适用于以零开头的二进制文件的压缩,原理就是统计有多少个0,或1,将其转化为数字。
需要压缩的文件
000000000001111111111111111
00000000111111111000000000
000000000001111111111100000000
00000000000111111111111
000000000001111111111111
00000000000011111111111

需要解压的文件
11 16
8 9 9
11 11 8
11 12
11 13
12 11

class RLC
{
private:
	std::ifstream *f;
public:
	RLC(std::ifstream &file)
	{
		f = &file;
	}
	void expend()
	{
		bool b=0;
		std::string str;
		while (!f->eof())
		{
			std::getline(*f, str);
			for (auto s : split(str, " "))
			{
				int n = std::stoi(s);
				for (int i = 0; i < n; i++)
				{
					printf("%d",b);
				}
				b = !b;
			}
			printf("\n");
		}
	}
	void compress()
	{
		std::string str;
		while (!f->eof())
		{
			int count = 0;
			std::getline(*f, str);
			char c = str[0];
			for (int i = 0; i < str.length(); i++)
			{
				if (str[i] == c)
				{
					count++;
				}
				else
				{
					printf("%d ", count);
					c = str[i];
					count = 1;
				}
			}
			printf("%d\n",count);
		}
	}
};
运行结果

在这里插入图片描述
在这里插入图片描述
由于我们的c++没有split方法……所以,我从网上抄了一个,效果还不错。
转载自此处

std::vector<std::string> split(std::string str, std::string pattern)
{
	std::string::size_type pos;
	std::vector<std::string> result;
	str += pattern;//扩展字符串以方便操作
	int size = str.size();
	for (int i = 0; i < size; i++)
	{
		pos = str.find(pattern, i);
		if (pos < size)
		{
			std::string s = str.substr(i, pos - i);
			result.push_back(s);
			i = pos + pattern.size() - 1;
		}
	}
	return result;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值