CACHE在C 中遗忘的矩阵换位实现
Cache Oblivious Matrix Transposition Implementation in C++
我已经实现了c 中的cache-oblivious矩阵transrix算法:
void CacheObliviousTransposition(int x, int delx, int y, int dely, int N, int* matrix) {
if ((delx == 1) && (dely == 1)) {
int tmp = matrix[(N*y) + x];
matrix[(N*y) + x] = matrix[(N*x) + y];
matrix[(N*x) + y] = tmp;
return;
}
if (delx >= dely) {
int xmid = delx / 2;
CacheObliviousTransposition(x, xmid, y, dely, N, matrix);
CacheObliviousTransposition(x + xmid, delx - xmid, y, dely, N, matrix);
return;
}
int ymid = dely / 2;
CacheObliviousTransposition(x, delx, y, ymid, N, matrix);
CacheObliviousTransposition(x, delx, y + ymid, dely - ymid, N, matrix);
}
但是,当我在换位后调用以下方法以确保其正常工作时,IF循环正在输入,因此我认为实现的某些问题必须是错误的。
void CheckTransposition(int N, int* matrix)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (matrix[(i*N) + j] != (j*N) + i + 42)
{
cout << "Transposition failed at i=" << i << ", j=" << j << "n";
}
}
}
}
谁能帮我确定什么问题?
注意:变量矩阵是一个动态分配的整数数组,如下所示,因为矩阵在n*n连续的内存位置中逐行存储
int* MatrixInit(int N)
{
int* matrix = new int[N*N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[(i*N) + j] = (i*N) + j + 42;
}
}
return matrix;
}
上述代码将两次转置您的元素。例如,一旦cacheoblivioustransposition到达单个元素[0,1],它将用[1,0]将其转换。但是,稍后将进行单独的递归[1,0],并再次使用[0,1]转置。最终,所有元素都将回到原来的地方。
为了确保仅转移一次元素,您可以在切换之前检查x小于y:
void CacheObliviousTransposition(int x, int delx, int y, int dely, int N, int* matrix) {
if ((delx == 1) && (dely == 1)) {
if(x<y)
{
int tmp = matrix[(N*y) + x];
matrix[(N*y) + x] = matrix[(N*x) + y];
matrix[(N*x) + y] = tmp;
}
return;
}
if (delx >= dely) {
int xmid = delx / 2;
CacheObliviousTransposition(x, xmid, y, dely, N, matrix);
CacheObliviousTransposition(x + xmid, delx - xmid, y, dely, N, matrix);
return;
}
int ymid = dely / 2;
CacheObliviousTransposition(x, delx, y, ymid, N, matrix);
CacheObliviousTransposition(x, delx, y + ymid, dely - ymid, N, matrix);
}
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- CACHE在C 中遗忘的矩阵换位实现