移植 C++使用 std::accumulate 映射到 PHP

发布于 2024-12-02 13:30:56 字数 1182 浏览 0 评论 0原文

我不太熟悉 PHP 中的数组操作,所以我有一个简单的移植问题。在 C++ 中,我有一个映射 std::map,其中键上的隐式排序是结构的关键部分。我想要做的是总结初始范围的键的所有值,我这样做:

// accumulate helper, since "value_type" is "pair<int, int>"
int pair_adder(int n, const std::map<int, int>::value_type & 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);
}

What would be a idioma way to write this data Structure and Accumulator in PHP?

解释一下上下文:数据结构是一个简单的时间序列,我想知道在时间 N 时我积累了多少。 C++ map 始终按键排序,因此我可以按任意顺序添加元素 mymap[time] = value;,并且地图始终包含按时间顺序排列的元素。

解释一下累积:accumulate 函数将键不大于 N 的所有映射值相加。例如,拿这张地图:

 mymap = { { 1, 20}, {2, 30}, {3, -10}, {4, 15} };

然后,对于 N = 2,我累积 50,对于 N = 3,我累积 40,对于 N = 12我累计了 55 个。


更新:我刚刚意识到实际上没有理由每个时间戳只出现一次,因此数据结构实际上应该是 std::multimap。相同的累积函数逐字工作,但如果 PHP 解决方案需要时间作为数组键,则该功能将不再工作。但这并不是绝对重要的。我相信每次都要求唯一的解决方案就足够了。

I'm not terribly well versed with array manipulation in PHP, so I have a simple porting question. In C++ I have a map std::map<int, int>, 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:

// accumulate helper, since "value_type" is "pair<int, int>"
int pair_adder(int n, const std::map<int, int>::value_type & 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);
}

What would be an idiomatic way to write this data structure and accumulator in PHP?

To explain the context: The data structure is a simple time series, and I want to know how much I have accumulated at time N. The C++ map is always sorted by key, so I can add elements mymap[time] = value; in any order, and the map always contains the elements in time order.

To explain the accumulation: The accumulate function sums up all the map's values whose keys are no greater than N. For example, take this map:

 mymap = { { 1, 20}, {2, 30}, {3, -10}, {4, 15} };

Then for N = 2 I accumulate 50, for N = 3 I accumulate 40, and for N = 12 I accumulate 55.


Update: I just realized that actually there's no reason why each timestamp should occur only once, so the data structure should really be a std::multimap<int, int>. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

叹沉浮 2024-12-09 13:30:56

我对 C++ 不太熟悉,但我会尝试向您快速概述 PHP 中的数组,然后回答您有关求和的问题。

PHP 中的每个数组都可以被视为有序映射。与 C++ 不同,数组没有类型限制,只是从键到值的映射。

要创建数组,您可以使用以下方法:

$arr = array();

要向数组添加项目,有两种方法。首先,您可以使用 [] 运算符将新元素添加到数组末尾。该元素的键为 (highest int key + 1),第一个键从零开始。例如:

$arr[] = 1;
$arr[] = 2;
$arr[] = 4;

此时, $arr 现在是一个具有以下键/值的映射:

0 => 1
1 => 2
2 => 4

我们还可以添加特定的键和值:

$arr[42] = 'cool';
$arr['foo'] = 'bar';

此时映射将如下所示:

0 => 1
1 => 2
2 => 4
42 => 'cool'
'foo' => 'bar'

PHP 内置了很多用于处理数组的函数。例如,有一些函数用于对数组进行排序(按键和值,以及以用户定义的方式)、组合数组、搜索数组、将函数应用于所有元素、减少数组等。此外,PHP 构造 foreach< /code> 可用于迭代数组。按如下方式使用它:

foreach ($arr as $key => $value) {
    echo 'Value of key ' . $key . ' is ' . $value;
}

现在,解决您的问题:

我想要做的是总结初始范围内的键的所有值

请注意,如果按顺序添加值,它们将在数组中按顺序排列。如果不是这种情况,请预先对数组进行排序,然后执行以下操作:

$sum = array_sum(array_slice($arr, 0, $n));

希望这会有所帮助!

I'm not super familiar with C++, but I'll try to give you a quick overview of arrays in PHP, then answer your question about summing.

Every array in PHP can be thought of as an ordered map. Unlike C++, there are no restrictions on type, an array is simply a map from key to value.

To create an array, you can use the following:

$arr = array();

To add items to the array, there are two ways to do it. First, you can use the [] operator to add a new element on to the end of the array. The key for this element will be (highest int key + 1), with the first key starting at zero. For example:

$arr[] = 1;
$arr[] = 2;
$arr[] = 4;

At this point, $arr is now a map with the following keys / values:

0 => 1
1 => 2
2 => 4

We can also add specific keys and values:

$arr[42] = 'cool';
$arr['foo'] = 'bar';

At this point the map will look as follows:

0 => 1
1 => 2
2 => 4
42 => 'cool'
'foo' => 'bar'

There's quite a few functions built in to PHP for working with arrays. For example, there are functions for sorting arrays (both by key and value, and in user defined ways), combining arrays, searching arrays, applying functions to all elements, reducing arrays, etc. Furthermore, the PHP construct foreach can be used to iterate over an array. Use it as follows:

foreach ($arr as $key => $value) {
    echo 'Value of key ' . $key . ' is ' . $value;
}

Now, to address your question:

What I want to do is to sum up all the values for an initial range of keys

Take note that if you add values in order, they will be in order in the array. If this is not the case, sort the array beforehand, then do the following:

$sum = array_sum(array_slice($arr, 0, $n));

Hope this helps!

反话 2024-12-09 13:30:56

不幸的是,PHP 数组映射/归约函数仅映射值,而不映射键。如果您的地图使用 PHP key =>; value 数组,您需要一些技巧来过滤掉键具有特定值的值。最简单的是直接循环:

$map = array(1 => 20, 2 => 30, 3 => -10, ...);
$n = 3;

$result = 0;
foreach ($map as $key => $value) {
    if ($key <= $n) {
        $result += $value;
    }
}

从这里您当然可以发挥创意:

$result = array_sum(array_intersect_key(
    $map,
    array_flip(array_filter(array_keys($map), function ($key) use ($n) {
        return $key <= $n;
    }))
));

或者:

$result = array_sum(array_map(function ($key, $value) use ($n) {
    return $key <= $n ? $value : 0;
}, array_keys($map), $map));

如果您使用更像 C++ 的映射(在 PHP 中将是数组的数组),这会简化问题:

$map = array(array('key' => 1, 'value' => 20), array(...), ...);

$result = array_reduce($map, function ($v, $m) use ($n) {
    return $v + ($m['key'] <= $n ? $m['value'] : 0);
});

Unfortunately, the PHP array map/reduce functions only map over values, not keys. If your map is using PHP key => value arrays, you'll need some tricks to filter out the values whose keys have a certain value. The easiest is a straight forward loop:

$map = array(1 => 20, 2 => 30, 3 => -10, ...);
$n = 3;

$result = 0;
foreach ($map as $key => $value) {
    if ($key <= $n) {
        $result += $value;
    }
}

From here you can of course get creative though:

$result = array_sum(array_intersect_key(
    $map,
    array_flip(array_filter(array_keys($map), function ($key) use ($n) {
        return $key <= $n;
    }))
));

Or:

$result = array_sum(array_map(function ($key, $value) use ($n) {
    return $key <= $n ? $value : 0;
}, array_keys($map), $map));

If you're using a more C++ like map, which in PHP would be an array of arrays, that simplifies the problem:

$map = array(array('key' => 1, 'value' => 20), array(...), ...);

$result = array_reduce($map, function ($v, $m) use ($n) {
    return $v + ($m['key'] <= $n ? $m['value'] : 0);
});
网名女生简单气质 2024-12-09 13:30:56

好吧,有 array_reduce 和一个地图基本上只是一个数组。因此:

$result = array_reduce($your_array, function($a, $b) { return $a + $b; });

应该解决这个问题。或者只是使用 array_sum (谢谢,德泽)。

Well, there’s array_reduce and a map is basically just an array. Hence:

$result = array_reduce($your_array, function($a, $b) { return $a + $b; });

should do the trick. Or just use array_sum (thanks, deceze).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文