2014-03-26 40 views
0

迭代至1D陣列(僞2D)以3步驟:迭代至1D陣列和二維陣列步驟

arr = new int[height * width * 3]; 
for (int i = 0; i < height * width * 3; i+=3) { 
    arr[i] = 1; 
} 

我已試過,但我得到的是三分之一的柱:

for (int y = 0; y < height * 3; y++) { 
    for (int x = 0; x < width; x+=3) { 
     arr[x + width * y] = 1; 
    } 
} 

回答

2

假設您的單元格具有3個條目的「大小」,則應在內部循環上使用* 3。否則,你會錯過每行三分之二的細胞。 您還需要將width乘以3才能得到正確的行。

for (int y = 0; y < height; y++) { 
    for (int x = 0; x < width * 3; x+=3) { 
     arr[x + width * 3 * y] = 1; 
    } 
} 

一般來說,你需要這樣的情況下,結構如下:

for (int y = 0; y < height; y++) { 
    for (int x = 0; x < width * cellWidth; x+= cellWidth) { 
     arr[x + width * cellWidth * y] = 1; 
    } 
} 

(分別爲cellWidth是3你的情況)

要稍微簡化這一點,你可以在循環假設您的單元格的寬度爲1(與正常情況類似),並在實際分配值時乘以cellWidth

for (int y = 0; y < height; y++) { 
    for (int x = 0; x < width; x++) { 
     int index = (x + width * y) * cellWidth; 
     arr[index + 0] = 1; // First 'cell entry' 
     arr[index + 1] = 1; // Second 
     ... 
     arr[index + cellWidth - 1] = 1; // Last 
    } 
} 

另一種解決方案是創建「大項目」使用struct例如:

typedef struct { int r, int g, int b } t_rgb; 
t_rgb* arr = new t_rgb[height * width]; 
for (int y = 0; y < height; y++) { 
    for (int x = 0; x < width; x++) { 
     arr[x + width * y].r = 1; 
    } 
} 

,你可以使用它作爲一個普通陣列(編譯器完成所有的計算你)。這也使得它更清楚你的代碼中發生了什麼。

1

你想要完成什麼?在RGB圖像中設置通道? 我通常不喜歡這樣:

for (int y = 0; y < height; y++) 
    for (int x = 0; x < width; x++) 
     arr[(x + width * y) * 3] = 1; 

一般來說,設置RGB值,你可以簡單地添加這樣的偏移:

for (int y = 0; y < height; y++) 
    for (int x = 0; x < width; x++) 
    { 
     size_t base = (x + width * y) * 3; 
     arr[base + 0] = r; 
     arr[base + 1] = g; 
     arr[base + 2] = b; 
    } 
+1

是,紅色通道 – rluks