[英]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.