在应用变量函数的矩阵元素上循环
Loop over matrix elements applying variable function
在我的矩阵类中,的实例太多
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;
}
相关文章:
- 擦除while循环中迭代的元素
- C++:如何循环通过向量中的整数元素
- 对于set上的循环-获取next元素迭代器
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- C++基于范围的 for 循环和元素副本
- 这个返回元素位置的基于循环的函数有什么问题?
- 为什么我在尝试在单向链表中打印元素时会出现这个永无止境的循环
- 循环访问还包含未使用元素的字符串数组
- C++用于循环跳过向量的元素?
- 基于相邻元素 c++ 的分段误差范围的循环
- 循环中的变量被设置为下一个数组的元素始终具有相同的内存地址?
- 使用现代C++在 Eigen3 矩阵上使用 for 循环进行元素操作的优雅方式
- 需要帮助编写一个小程序来将循环乘以 n 个元素和 k 个多重性
- C++ 数据结构队列:使用 for 循环查找队列中最大的元素
- 将函数应用于特征矩阵中的所有元素,而无需循环
- 使用 C++ 从每个循环的数组中选择 n 个元素
- 忽略元素的基于范围的 for 循环
- 优先级队列(使用 pairs<int,int> ) 根据 for 循环迭代器的顶级元素
- 用于随机访问和元素循环的最佳数据结构(C++)