Advertisement
Guest User

Untitled

a guest
Dec 1st, 2015
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. #include <vector>
  2. #include <unordered_map>
  3. #include <algorithm>
  4. #include <stdexcept>
  5. #include <utility>
  6. #include <functional>
  7. #include <string>
  8. using std::string;
  9. using std::vector;
  10. using std::function;
  11. using std::unordered_map;
  12. using std::pair;
  13.  
  14. template<typename T, typename H = std::hash<T>>
  15. class Docum{
  16. private:
  17. T initial_state;
  18. T current_state;
  19. H state_hash;
  20. vector<pair<function<void(T&)>, int>> operation;
  21. unordered_map<int, T> save_state;
  22. public:
  23. Docum(const T &s) :initial_state(s), current_state(s), state_hash() {
  24. save_state[0] = initial_state;
  25. };
  26. const &T get() const { return current_state; }
  27. void checkout(int n){
  28. assert(abs(n) < operation.size());
  29. unsigned int step = 0;
  30. if (n < 0) step = operation.size() + n;
  31. else step = n;
  32. operation.resize(step);
  33. auto up = save_state.upper_bound(step);
  34. --up;
  35. current_state = up->second;
  36. for (int i = up->first; i < step){
  37. operation[i].first(current_state);
  38. }
  39. if (state_hash(current_state) != operation[step - 1].second){
  40. throw std::logic_error("Hash does not match!");
  41. }
  42. }
  43. void apply(const function<void(T&)> &f){
  44. operation.push_back({ f, state_hash(current_state) });
  45. f(current_state);
  46. }
  47. void save_current(){
  48. save_state[operation.size()] = current_state;
  49. }
  50. };
  51.  
  52. template <typename T>
  53. Docum<T> make_doc(const T& temp){
  54. return Docum<T>(temp);
  55. }
  56.  
  57.  
  58. void delete_symbol(string &s){
  59. s.pop_back();
  60. }
  61.  
  62. int main(){
  63.  
  64. Docum<string> doc("127fhfhe67df");
  65. for (int i = 0; i < 3; ++i){
  66. doc.apply(delete_symbol);
  67. }
  68.  
  69. system("pause");
  70. return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement