You are viewing a single comment's thread. Return to all comments →
class ICommand { public: virtual void execute() =0; virtual void undo()=0; virtual ~ICommand() {}; }; class AppandCommand:public ICommand { private: string& sref; string append_text; public: AppandCommand(string& strref,const string& appandtext):sref(strref),append_text(appandtext){} void execute() override { sref += append_text; }; void undo() override { int N=sref.size(); sref.erase(N - append_text.size()); }; /* ~AppandCommand() { } */ }; class DeleteCommand :public ICommand { private: string& sref; int delete_count; string deleted_str; public: DeleteCommand(string& strref, int delete_count1) :sref(strref), delete_count(delete_count1) {} void execute() override { //sref += append_text; int N = sref.size(); deleted_str = sref.substr(N - delete_count, delete_count); sref.erase(N - delete_count); }; void undo() override { int N = sref.size(); sref += deleted_str; }; /* ~DeleteCommand() { } */ }; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int Q; cin >> Q; string S; stack<shared_ptr<ICommand>> cmds; string wholeline; string strOP = ""; string strValue = ""; for (int i = 0; i < Q; ++i) { getline(std::cin >> std::ws, wholeline); //stringstream ss(wholeline); //getline(ss, strOP, ' '); char operation_id = wholeline[0]; if (operation_id != '4') { strValue = wholeline.substr(2); } if (operation_id == '1') { shared_ptr<ICommand> cmd = make_shared<AppandCommand>(S, strValue); cmd->execute(); cmds.push(cmd); } else if (operation_id == '2') { int delete_count = stoi(strValue); shared_ptr<ICommand> cmd = make_shared<DeleteCommand>(S, delete_count); cmd->execute(); cmds.push(cmd); } else if (operation_id == '3') { int index = stoi(strValue); cout << S[index - 1] << "\n"; } else if (operation_id == '4') { shared_ptr<ICommand> cmd = cmds.top(); cmd->undo(); cmds.pop(); } } return 0; }
Seems like cookies are disabled on this browser, please enable them to open this website
Simple Text Editor
You are viewing a single comment's thread. Return to all comments →