有没有一种简单的方法可以在 C++ 中进行数组差分和近似数组导数? (类似于matlab中的diff()函数)

Is there a simple way to do array differences and approximate array derivatives in C++? (Like the diff() function in matlab)

我想将 Matlab 代码翻译成 C++

X = [1 1 2 3 5 8 13 21]; 
Y = diff(X)

输出:0 1 1 2 3 5 8

https://www.mathworks.com/help/matlab/ref/diff.html

#include <iostream>

void diff(int params[], int length) {
    for (size_t i = 0; i < length - 1; i++) {
        std::cout << params[i + 1] - params[i] << " ";
    }
}
int main() {
    int x[] = { 1,1,2,3,5,8,13,21 };
    int length =std::size(x); 
    diff(x, length);
    return 0;
}

输出:

0 1 1 2 3 5 8

在 C++20 之前,没有直接类似于 Matlabs diff 的标准算法,但您可以使用 std::transform:

#include <algorithm>
#include <vector>
#include <iostream>
#include <functional>


std::vector<int> diff(const std::vector<int>& x) {    
    if (x.size()==0) return {};
    std::vector<int> result(x.size()-1);
    std::transform(x.begin()+1,x.end(),x.begin(),result.begin(),std::minus<int>{});
    return result;
}


int main() {
    std::vector<int> x{1,3,4,5,6,10};
    auto d = diff(x);
    for (const auto& e : d) std::cout << e << " ";
}

std::minus<int>{}是一个函数对象,returns它的参数之间的区别。它与 std::transform 一起用作二元运算符来计算排除第一个元素的 x 和排除最后一个元素的 x 之间的元素差异(对于第二个输入范围,只有范围的开始是传递给 std::transform).

Live Demo

有关可在 C++20 中使用的算法,请参阅

非常天真的实现:

#include <vector>
#include <iostream>

template <typename T>
std::vector<T> diff(const std::vector<T>& array){
    std::vector<T> result;
    for(int i = 1; i < array.size(); ++i){
        result.push_back(array[i] - array[i-1]);
    }
    return result;
}

注意:您还可以在类型 T 上添加约束,请随时查阅 C++ 文档。

C++ 调用它 std::adjacent_difference.

int X[8] = {1, 1, 2, 3, 5, 8, 13, 21}; 
int Y[8];

std::adjacent_difference( std::begin(X), std::end(X), std::begin(Y) );

请注意,目标的第一个元素是源的直接副本。剩下的元素就是差异。

See it work on Compiler Explorer.