Loop over matrix elements applying variable function

爷,独闯天下 提交于 2019-12-14 03:59:48

问题


In my matrix class there are too many instances of

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

Keeping in mind the DRY principle , I was wondering whether I could

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
       }
    }
}

So that when I want to loop over and apply something to the matrix I just have to call loopApply(fn)

Is there any way to do this ? Or is there a better approach to do this ?
Thank You.

UPDATE I am looking for a general way to do this. So that fn does not have to take a single parameter etc. I have heard about variadic parameters , but I could not understand how they work , or if they are suited for the job.

Minimal Code:

// 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 

回答1:


It looks like

#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;
}


来源:https://stackoverflow.com/questions/29447546/loop-over-matrix-elements-applying-variable-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!