c++ - 使用STL算法计算绝对值之和

标签 c++ stl stl-algorithm reduction

我想使用std::numeric算法来计算数组的绝对值之和,以便使用gnu并行扩展(数组大小> 500000)。

这是我当前的代码:

double ret = 0;
for (auto i = 0U; i < length; ++i)
{
    ret += std::abs(tab[i]);
}
return ret;

所以我考虑这样做:

auto sumabs = [] (double a, double b) 
{
    return std::abs(a) + std::abs(b);
} 

std::accumulate(tab, tab + length, 0, sumabs);

但它效率低下,因为如果执行归约算法(我真诚地希望为了快速计算!),std::abs 将应用于已经 >= 0 的值.

那么有什么办法可以做到这一点吗?也许“手动”执行减少的第一步,然后让 std::accumulate 在其余部分之间进行简单的加法?但会有拷贝和内存命中...

最佳答案

您可以将函数传递给 Accumlate 方法并在函数内执行“手动”计算。顺便说一句,在您的代码中,您将 abs 方法应用于第一个参数,这是不必要的。

int fAccumulate (int accumulated, int accumulateIncrement) 
{
    int retValue = 0;
    if (accumulateIncrement >= 0)
    {
        retValue = accumulated + accumulateIncrement;
    }
    else
    {
        retValue = accumulated + std::abs(accumulateIncrement);
    }
    return retValue;
}

此代码的用途可能是:

int init = 0;
int numbers[] = {10,20,-30};
int a = std::accumulate (numbers, numbers+3, init, fAccumulate);

关于c++ - 使用STL算法计算绝对值之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18049965/

相关文章:

c++ - 在构造函数初始化列表中向 STL 映射添加元素?

c++ - STL 计数算法返回不正确的值。

algorithm - 为什么是 `copy_n` 、 `fill_n` 和 `generate_n` ?

c++ - .natvis - 如何引用模板模板参数?

c++ - 在 dll 中导出 C++ 类的问题

c++ - 基于第一对的 "first"对 <std::pair<int, std::pair<int, int>>> 类型的 std::vector 进行排序的标准方法是什么

c++ - 类指针 vector 上的 std::sort()

c++ - CPPUnit 数组断言

c++ - 优化 C++ 中的大整数减法

c++ - 将带有指针的 std 列表复制到另一个带有指针的 std 列表