Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Prasoon has already offered up a host of different (and good) ways to do this, none of which need repeating here. I'd like to suggest an alternative approach for speed however.</p> <p>If you're going to be doing this quite a bit, you may want to consider "sub-classing" your vector so that a sum of elements is maintained separately (not <em>actually</em> sub-classing vector which is iffy due to the lack of a virtual destructor - I'm talking more of a class that contains the sum and a vector within it, <code>has-a</code> rather than <code>is-a</code>, and provides the vector-like methods).</p> <p>For an empty vector, the sum is set to zero. On every insertion to the vector, add the element being inserted to the sum. On every deletion, subtract it. Basically, <em>anything</em> that can change the underlying vector is intercepted to ensure the sum is kept consistent.</p> <p>That way, you have a very efficient O(1) method for "calculating" the sum at any point in time (just return the sum currently calculated). Insertion and deletion will take slightly longer as you adjust the total and you should take this performance hit into consideration.</p> <p>Vectors where the sum is needed more often than the vector is changed are the ones likely to benefit from this scheme, since the cost of calculating the sum is amortised over all accesses. Obviously, if you only need the sum every hour and the vector is changing three thousand times a second, it won't be suitable.</p> <p>Something like this would suffice:</p> <pre><code>class UberVector: private Vector&lt;int&gt; vec; private int sum; public UberVector(): vec = new Vector&lt;int&gt;(); sum = 0; public getSum(): return sum; public add (int val): rc = vec.add (val) if rc == OK: sum = sum + val return rc public delindex (int idx): val = 0 if idx &gt;= 0 and idx &lt; vec.size: val = vec[idx] rc = vec.delindex (idx) if rc == OK: sum = sum - val return rc </code></pre> <p>Obviously, that's pseudo-code and you may want to have a little more functionality, but it shows the basic concept.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload