如何使用指针为矩阵编写单循环

How to write single loop for a matrix using pointers

本文关键字:单循环 何使用 指针      更新时间:2023-10-16

为什么我不能使用下面的代码?我知道矩阵的定义就像一个一维数组,后面跟着一个。

我怎样才能使它成为可能?

我所需要的只是优化

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(行*列)。