Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <unordered_map>
- #include <algorithm>
- #include <stdexcept>
- #include <utility>
- #include <functional>
- #include <string>
- using std::string;
- using std::vector;
- using std::function;
- using std::unordered_map;
- using std::pair;
- template<typename T, typename H = std::hash<T>>
- class Docum{
- private:
- T initial_state;
- T current_state;
- H state_hash;
- vector<pair<function<void(T&)>, int>> operation;
- unordered_map<int, T> save_state;
- public:
- Docum(const T &s) :initial_state(s), current_state(s), state_hash() {
- save_state[0] = initial_state;
- };
- const &T get() const { return current_state; }
- void checkout(int n){
- assert(abs(n) < operation.size());
- unsigned int step = 0;
- if (n < 0) step = operation.size() + n;
- else step = n;
- operation.resize(step);
- auto up = save_state.upper_bound(step);
- --up;
- current_state = up->second;
- for (int i = up->first; i < step){
- operation[i].first(current_state);
- }
- if (state_hash(current_state) != operation[step - 1].second){
- throw std::logic_error("Hash does not match!");
- }
- }
- void apply(const function<void(T&)> &f){
- operation.push_back({ f, state_hash(current_state) });
- f(current_state);
- }
- void save_current(){
- save_state[operation.size()] = current_state;
- }
- };
- template <typename T>
- Docum<T> make_doc(const T& temp){
- return Docum<T>(temp);
- }
- void delete_symbol(string &s){
- s.pop_back();
- }
- int main(){
- Docum<string> doc("127fhfhe67df");
- for (int i = 0; i < 3; ++i){
- doc.apply(delete_symbol);
- }
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement