gpt4 book ai didi

c++ - 使用 C++11 进行转换和累加

转载 作者:行者123 更新时间:2023-11-28 00:14:36 24 4
gpt4 key购买 nike

来自 Python 我想知道现在的 C++ 是否有 Python 中的一些好的功能。

目前我正在尝试弄清楚如何使用索引来生成一些元素的总和。例如,对于 Python,我会:

a = [ ... ]
b = [ ... ]

sum(map(lambda i: a[i] * 2 - b[i + 1], range(len(a)))

所以在这里我生成了一个新数组,其中每个元素都由一些索引算法确定。

STL 中有transformaccumulate,但它们以迭代器为参数。如果我只需要在每个步骤上更改一个具体元素,这就可以了。这里我需要用到索引。

还有 transform 我必须指定我需要将结果放入的数组。有没有办法动态生成结果数组然后返回?类似于 Python 的 map

因为在这种情况下,编写一个简单的 for 循环确实更容易。

最佳答案

无需创建中间数组,只需将 std::transform 排除在外。您只需要 std::accumulate 对中间结果求和即可。但是,正如您所指出的,这涉及跳过几个环节以获得给定迭代器的索引。

int a[] = {10, 20, 30, 40};
int b[] = {1, 2, 3, 4, 5};

std::accumulate(std::begin(a), std::end(a), 0,
[&](int acc, int& a_elem) {
auto index = std::distance(a, &a_elem);
return acc + a[index] * 2 - b[index + 1];
})

Live demo

如果可以使用 Boost.Range,这可以清理很多反而。这将允许您生成一系列可用作索引的整数,与您的 Python 示例非常相似。

boost::accumulate(boost::irange<unsigned>(0, boost::size(a)), 0,
[&](int acc, int index) {
return acc + a[index] * 2 - b[index + 1];
})

Live demo

关于c++ - 使用 C++11 进行转换和累加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31173910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com