我想为我必须要做的CS项目创建一个RLE压缩和解压缩方法。问题不在于逻辑,而在于C ++的专有技术。我目前在学校学到的只有Python,所以我尝试用Python做这个项目,这真的很容易......
我打算用C ++阅读,但今晚没有足够的时间。我希望得到帮助,因为如果我能理解相同的C ++代码,我可能会对这种语言感觉更舒服。
有人可以帮助我将以下python代码转换为C ++等效代码吗?
# compresses data using RLE compression
def compress(data):
letter_counter = 1
new_data = []
for i in range(len(data)):
try:
# if the element is the same as the next one
if data[i] == data[i + 1]:
letter_counter += 1
# if different element than previous index
else:
new_data.append(str(letter_counter) + data[i])
letter_counter = 1 # reset the letter count
except IndexError: # when the index is out of range (no more elements)
new_data.append(str(letter_counter) + data[i])
return new_data
data = ['w', 'w', 'w', 'w', 'w', 'b', 'b', 'b', 'c', 'd', 'e', 'e']
data2 = ['w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w']
return compress(data) # prints ['5w', '3b', '1c', '1d', '2e']
return compress(data2) # prints ['14w']
答案 0 :(得分:1)
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
string compress(string data) {
int letter_counter = 1, i=0;
ostringstream new_data;
for (i; i<data.length()-1; i++) {
if (data[i] == data[i+1]) {
letter_counter += 1;
} else {
new_data<<letter_counter;
new_data<<data[i];
letter_counter = 1;
}
}
new_data<<letter_counter;
new_data<<data[i];
return new_data.str();
}
int main() {
string data = string("wwwwwbbbcdee");
string data2 = string("wwwwwwwwwwwwww");
cout << compress(data) <<endl;
cout << compress(data2) <<endl;
}
这是使用C ++实现它的简单方法。它将字符数组视为字符串,并使用stringstream轻松地将数字插入字符串。
在一天结束时,其他海报是正确的。学习C ++的最好方法是在遇到问题时尝试自己并问别人。 www.cplusplus.com是一个很好的资源。
答案 1 :(得分:0)
只是旁注 - 你的Python可以大规模改进:
from itertools import groupby
print ['{}{}'.format(len(list(g)), k) for k, g in groupby(data)]