There are two cases: static data or dynamic (changing) data
1. Static data
For static data, this is a well-known issue. First, calculate the “sum table” (an array of n + 1 elements):
st[0] = 0; for (int i=0,n=x.size(); x<n; x++) st[i] = st[i-1] + x[i];
then to calculate the sum of the elements between a and b you just need to do
sum = st[b] - st[a];
The algorithm can also be used in higher dimensions. For example, if you need to calculate the sum of all values between (x0, y0) and (x1, y1), you can simply do
sum = st[y0][x0] + st[y1][x1] - st[y0][x1] - st[y1][x0];
where st[y][x] is the sum of all the elements above and to the left of (x, y) .
Calculating the sum table is an O (n) operation (where n is the number of elements, for example rows*columns for a 2d matrix), but for very large data sets (for example, images), you can write the optimal parallel version that can work in O ( n / m) , where m is the number of available CPUs. This is what I found quite unexpected ...
Performing a simple (single-threaded) calculation of the sum table in the case of 2d:
for (int y=0; y<h; y++) for (int x=0; x<w; x++) st[y+1][x+1] = st[y+1][x] + st[y][x+1] - st[y][x] + value[y][x];
2.Dynamic data
Instead of dynamic data, you can use what can be called "multi-mode":
void addDelta(std::vector< std::vector< int > >& data, int index, int delta) { for (int level=0,n=data.size(); level<n; level++) { data[level][index] += delta; index >>= 1; } } int sumToIndex(std::vector< std::vector< int > >& data, int index) { int result = 0; for (int level=0,n=data.size(); level<n; level++) { if (index & 1) result += data[level][index-1]; index >>= 1; } return result; } int sumRange(std::vector< std::vector< int > >& data, int a, int b) { return sumToIndex(data, b) - sumToIndex(data, a); }
Basically, at each "level" a cell contains the sum of two cells of the next more subtle levels. When you add data to the lowest (higher) level, you should also add it to higher levels (this is what addDelta does). To calculate the sum of all values from 0 to x , you can use higher levels to accumulate calculations ... see the following figure:

Finally, to get the sum from a to b , you simply calculate the difference between the two sums, starting at 0.