Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate C++ function automatically?

I want to write a c++ matrix operation code, some operation are the same for some function. I wonder whether there are some method to merge them? For example:

void add1(vector<vector<double> > &m){
    for(int i = 0; i < m.size(); ++i){
        for(int j = 0; j < m[i].size(); ++j){
            m[i][j] += 1.0;
        }
    }
}

void minus1(vector<vector<double> > &m){
    for(int i = 0; i < m.size(); ++i){
        for(int j = 0; j < m[i].size(); ++j){
            m[i][j] -= 1.0;
        }
    }
}

The two pieces of code is almost the same. How can I avoid to rewrite it for two times? Are there something like template that can generate code automatically?

like image 329
maple Avatar asked Dec 19 '22 17:12

maple


2 Answers

You can define a function template and put the core logic of iterating over the elements in that function.

The template parameter can be functor which can be used to define what happens for each specific call.

// Change m to be a reference so the modifications to the elements
// are visible in the calling function.

template <typename Functor>
void for_each_member(vector<vector<double> >& m, Functor functor)
{
   for(std::size_t i = 0; i < m.size(); ++i){
      for(std::size_t j = 0; j < m[i].size(); ++j){
         functor(m[i][j]);
      }
   }
}

void add1(vector<vector<double> >& m){
   for_each_member(m, [](double& item) { item += 1.0;});
}

void minus1(vector<vector<double> >& m){
   for_each_member(m, [](double& item) { item -= 1.0;});
}
like image 73
R Sahu Avatar answered Dec 24 '22 02:12

R Sahu


You could generalize in the following manner:

template<typename T, typename F>
void for_each_element(std::vector<std::vector<T>> &m, F &&f) {
  std::for_each(m.begin(), m.end(), [f] (auto &&v) {
    std::transform(v.begin(), v.end(), v.begin(), f);
  });
}

Live Demo

Mind however, that representing a matrix as a std::vector<std::vector<T>> is not very cache friendly, since you disparse the rows of the matrix all over the memory. It would be better if you had a custom matrix class that internally would use one std::vector and would overload the subscript operators for row/column major access.

like image 34
101010 Avatar answered Dec 24 '22 02:12

101010