在应用变量函数的矩阵元素上循环

Loop over matrix elements applying variable function

本文关键字:元素 循环 应用 变量 函数      更新时间:2023-10-16

在我的矩阵类中,的实例太多

for(size_t i = 1 ; i <= rows ; i++){
   for(size_t j = 1 ; i <= cols ;j++){
     //Do something
   }
}

记住DRY原则,我想知道我是否可以

matrix<T>::loopApply(T (*fn) (T a)){ // changed T to T a
    for(size_t i = 1 ; i <= rows ; i++){
       for(size_t j = 1 ; i <= cols ;j++){
         _matrix[(i-1)*_rows + (j-1)] = fn(a) // changed T to a
       }
    }
}

因此,当我想循环并将一些东西应用到矩阵时,我只需要调用loopApply(fn)

有办法做到这一点吗?或者有更好的方法来做到这一点吗
非常感谢。

更新我正在寻找一个通用的方法来做到这一点。因此,fn不必采用单个参数等。我听说过可变参数,但我不知道它们是如何工作的,也不知道它们是否适合这份工作。

最小代码:

// in matrix.h
template <class T>
class matrix
{
    public:
     ...
    private:
     ...
     std::vector<T> _matrix;
     void loopApply(T (*fn) (T) );
}
#include "matrix.tpp"
//in matrix.tpp
template <class T> // Template to template // Pointed out in comment
 // loopApply as written above 

它看起来像

#include <iostream>
struct A
{
    enum { N = 10 };
    int a[N][N];
    template <typename Fn, typename ...Args>
    void method( Fn fn, Args...args )
    {
        for ( size_t i = 0; i < N; i++ )
        {
            for ( size_t j = 0; j < N; j++ ) a[i][j] = fn( args... );
        }
    }
};  
int main() 
{
    return 0;
}