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?
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;});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With