[英]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出了什么问题。 在一维中遍历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(行*列)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.