The task is to define the class ‘RleCodec’ for run-length encoding:
The rule of run-length encoding is simple: Count the number of consecutive repeated characters in a string, and replace the repeated characters by the count and a single instance of the character. For example, if the input string is ‘AAADDDDDDDBBGGGGGCEEEE’, its run-length encoding will be ‘3A7DBB5GC4E’, because there are three A’s, seven D’s, … etc. Note that we do not need to encode runs of length one or two, since ‘2B’ and ‘1C’ are not shorter than ‘BB’ and ‘C’.
We first design the abstract base class ‘Codec’ as an interface, which contains two pure virtual functions encode() and decode():
class Codec { public: Codec(std::string s): encoded{false}, code_str{s} { } virtual ~Codec() { } // virtual destructor; do nothing virtual void encode() = 0; virtual void decode() = 0; void show(std::ostream& os) const { os << code_str; } bool is_encoded() const { return encoded; } protected: bool encoded; std::string code_str; };
TODOs: In ‘function.cpp’, please
Codec* getCodec(const std::string& type, const std::string& is);
For more information, you should refer to the main.cpp and function.h.
Note
It is highly recommended to practice std::stringstream in this problem. Here is a simple code that shows you how to use stringstream:
#include <iostream>
#include <sstream> // header file for stringstream
using namespace std;
int main(){
string s;
stringstream ss;
getline(cin, s);
ss << s;
while(!ss.eof()){
string t;
getline(ss, t, ' ');
cout << t << "\n";
}
return 0;
}
/*
- Sample Input
This is a sentence for testing this code.
- Sample Output
This
is
a
sentence
for
testing
this
code.
*/
For more information, please refer to this article.
The input contains a single line that consists of several characters.
There are four lines.
The first and second lines are dummy encoding and decoding.
The third and fourth lines are RLE encoding and decoding.
Each line is followed by a new line character.