Skip to content

Commit

Permalink
feat(templates): vector with rollback
Browse files Browse the repository at this point in the history
  • Loading branch information
STommydx committed Apr 5, 2024
1 parent 9a8cdb4 commit a1b3a67
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
34 changes: 34 additions & 0 deletions utilities.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,38 @@ template <class T> struct magic_vector {
}
};

template <class T> class vector_rollback {
std::vector<T> data;
std::vector<std::pair<size_t, T>> history;

public:
static constexpr size_t last_version = -1;

template <class... Args>
vector_rollback(Args... args) : data(args...), history() {}
size_t size() const { return data.size(); }
size_t version() const { return history.size(); }
T modify(size_t i, T x) {
history.emplace_back(i, data[i]);
data[i] = x;
return x;
}
const T &front() const { return data.front(); }
const T &back() const { return data.back(); }
const T &operator[](size_t i) const { return data[i]; }
const T &at(size_t i) const { return data.at(i); }
void rollback(size_t version = last_version) {
if (version == last_version) {
if (history.empty())
return;
version = history.size() - 1;
}
while (history.size() > version) {
auto [i, x] = history.back();
history.pop_back();
data[i] = x;
}
}
};

#endif
15 changes: 15 additions & 0 deletions utilities_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,18 @@ TEST_CASE("compression_vector constructors", "[utilities]") {
v3.compress();
REQUIRE(v3[0] == "");
}

TEST_CASE("vector with rollback", "[utilities]") {
std::vector<int> v{2, 4, 3, 5, 8, 3, 5, 5};
vector_rollback<int> v2(v);
v2.modify(3, 10);
REQUIRE(v2[3] == 10);
v2.rollback();
REQUIRE(v2[3] == 5);
v2.modify(3, 10);
v2.modify(4, 10);
v2.modify(3, 5);
v2.rollback(1);
REQUIRE(v2[3] == 10);
REQUIRE(v2[4] == 8);
}

0 comments on commit a1b3a67

Please sign in to comment.