Note that there are some explanatory texts on larger screens.

plurals
  1. POPorting a C++ map with std::accumulate to PHP
    primarykey
    data
    text
    <p>I'm not terribly well versed with array manipulation in PHP, so I have a simple porting question. In C++ I have a map <code>std::map&lt;int, int&gt;</code>, for which the implicit ordering on the key is a crucial part of the structure. What I want to do is to sum up all the values for an initial range of keys, which I do like this:</p> <pre><code>// accumulate helper, since "value_type" is "pair&lt;int, int&gt;" int pair_adder(int n, const std::map&lt;int, int&gt;::value_type &amp; p) { return n + p.second; } // To add up values for keys up to N: int total_value_up_to_time_N(int N) { return std::accumulate(mymap.begin(), mymap.upper_bound(N), 0, pair_adder); } </code></pre> <p>What would be an idiomatic way to write this data structure and accumulator in PHP?</p> <p>To explain the context: The data structure is a simple time series, and I want to know how much I have accumulated at time <code>N</code>. The C++ <code>map</code> is always sorted by key, so I can add elements <code>mymap[time] = value;</code> in any order, and the map always contains the elements in time order.</p> <p>To explain the accumulation: The <code>accumulate</code> function sums up all the map's values whose keys are no greater than <code>N</code>. For example, take this map:</p> <pre><code> mymap = { { 1, 20}, {2, 30}, {3, -10}, {4, 15} }; </code></pre> <p>Then for <code>N = 2</code> I accumulate 50, for <code>N = 3</code> I accumulate 40, and for <code>N = 12</code> I accumulate 55.</p> <hr> <p><em>Update:</em> I just realized that actually there's no reason why each timestamp should occur only once, so the data structure should really be a <code>std::multimap&lt;int, int&gt;</code>. The same accumulation function works verbatim, but if the PHP solution requires the time to be an array key, than that would no longer work. But this is not strictly important; I believe a solution in which each time is required to be unique will suffice.</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.
 

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