如何使用指针为矩阵编写单循环
How to write single loop for a matrix using pointers
为什么我不能使用下面的代码?我知道矩阵的定义就像一个一维数组,后面跟着一个。
我怎样才能使它成为可能?
我所需要的只是优化
MyStructure* myStructure[8][8];
int i = 0;
for(MyStructure* s = myStructure[0][0]; i<64; i++,s++)
{
}
由于用指向对象的指针更难证明这一点,我用公共整数代替了指向MyStructure的指针。间接级别保持不变,间接级别对OP的问题很重要。
顺便说一下,不要这样做。使用Ediac的解决方案。我只是想指出OP哪里出了问题。在一维MAY中遍历2D阵列是可行的。可能不会。调试它很有趣!这只是因为将2D阵列实现为1D阵列很容易,但据我所知,这种行为并不能得到保证。矢量或其他传统的动态阵列解决方案肯定不能保证这一点。如果我错了,请扇我耳光。
#include <iostream>
using namespace std;
//begin function @ Seraph: Agreed. Lol.
int main()
{
// ordering the array backwards to make the problem stand out better.
// also made the array smaller for an easier demo
int myStructure[4][4] = {{16,15,14,13},{12,11,10,9},{8,7,6,5}, {4,3,2,1}};
int i = 0;
// here we take the contents of the first element of the array
for (int s = myStructure[0][0]; i < 16; i++, s++)
{ //watch what happens as we increment it.
cout << s << " ";
}
cout << endl;
// output: 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// this didn't iterate through anything. It incremented a copy of the first value
// reset and try again
i = 0;
// this time we take an extra level of indirection
for (int * s = &myStructure[0][0]; i < 16; i++, s++)
{
// and output the value pointed at
cout << *s << " ";
}
cout << endl;
// output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
// now we have the desired behaviour.
} //end function end Lol
输出:
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
如果一个循环就是你想要的,你可以这样做:
MyStructure* myStructure[8][8];
for(int i = 0; i<64; i++)
{
MyStructure* s = myStructure[i/8][i%8];
}
您将遍历矩阵的每个元素。然而,时间复杂性仍然是O(行*列)。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 为什么使用 "this" 指针调用派生成员函数?
- 使用新行和不使用新行读取文件
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 如何确定我已使用非编码文件到达 EOF?
- 使用单循环打印矩阵的L部分
- 使用 LLVM 的 libc++ 时,__1 符号从何而来?
- 在std::cout之后使用std::cin时,换行符从何而来
- 为什么以及在何处在C++中使用引用和指针
- 基例如何影响使用递归函数的哪些行
- 如何使用指针为矩阵编写单循环