Skip to content

Commit fcdc3be

Browse files
committed
feat: Add error handling for out-of-range access in PointAddRangeSum methods
1 parent 57475f7 commit fcdc3be

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

weilycoder/ds/point_add_range_sum.hpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
#include "group.hpp"
55
#include <cstddef>
6+
#include <stdexcept>
67
#include <vector>
78

89
namespace weilycoder {
@@ -58,6 +59,8 @@ template <typename Group> struct PointAddRangeSum {
5859
}
5960
}
6061

62+
size_t size() const { return data.size() - 1; }
63+
6164
/**
6265
* @brief Adds value x to element at index i
6366
* @param i Index to update
@@ -74,6 +77,8 @@ template <typename Group> struct PointAddRangeSum {
7477
* @return The sum of elements in the range [0, i)
7578
*/
7679
T prefix_sum(size_t i) const {
80+
if (i > size())
81+
throw std::out_of_range("Index out of range in prefix_sum");
7782
T result = Group::identity();
7883
for (; i > 0; i -= i & -i)
7984
result = Group::operation(result, data[i]);
@@ -87,6 +92,8 @@ template <typename Group> struct PointAddRangeSum {
8792
* @return The sum of elements in the range [l, r)
8893
*/
8994
T range_sum(size_t l, size_t r) const {
95+
if (l > r || r > size())
96+
throw std::out_of_range("Invalid range for range_sum");
9097
return Group::operation(prefix_sum(r), Group::inverse(prefix_sum(l)));
9198
}
9299
};

0 commit comments

Comments
 (0)