2013-02-20 20 views
4

如何訪問多維數組的整行? 例如:在C++中訪問多維數組的整行

int logic[4][9] = { 
    {0,1,8,8,8,8,8,1,1}, 
    {1,0,1,1,8,8,8,1,1}, 
    {8,1,0,1,8,8,8,8,1}, 
    {8,1,1,0,1,1,8,8,1} 
}; 

// I want everything in row 2. So I try... 
int temp[9] = logic[2]; 

我嘗試拋出錯誤:

array initialization needs curly braces

我知道我可以使用FOR循環檢索該行,不過我很好奇,如果有一個比較明顯的解決方案。

+1

可能的替代:'的std ::矢量溫度(標準::開始(邏輯[2]),標準::端(邏輯[2]));'? – hmjd 2013-02-20 21:43:41

+1

數組不是太C++。如果可以的話,使用'std :: vector'。 – 2013-02-20 21:44:26

+0

你可以看看['valarray'](http://en.cppreference.com/w/cpp/numeric/valarray)和['slice'](http://en.cppreference.com/w/cpp/數字/的valarray /片)。 – 2013-02-20 22:18:58

回答

5

這不是數組/指針在C++中的工作方式。

該數組存儲在內存中的某處。爲了引用相同的數據,你需要一個指向數組的開頭的指針:

int* temp = logic[2]; 

或者,如果你需要一個數組的副本,你將不得不分配更多的空間。

靜:

int temp[9]; 
for (int i = 0; i < 9; i++) { 
    temp[i] = logic[2][i]; 
} 

動態:

// allocate 
int* temp = new int(9); 
for (int i = 0; i < 9; i++) { 
    temp[i] = logic[2][i]; 
} 

// when you're done with it, deallocate 
delete [] temp; 

或者由於您使用C++,如果你想不用擔心這一切記憶的東西和指針,那麼你應該使用std::vector<int>爲動態調整大小的數組和std::array<int>用於靜態大小的數組。

#include <array> 
using namespace std; 

array<array<int, 9>, 4> logic = { 
    {0,1,8,8,8,8,8,1,1}, 
    {1,0,1,1,8,8,8,1,1}, 
    {8,1,0,1,8,8,8,8,1}, 
    {8,1,1,0,1,1,8,8,1} 
}}; 

array<int, 9> temp = logic[2]; 
2

直接分配不起作用。 C++不允許這樣做。最好你可以指定它們指向相同的數據 - int *temp = logic[2]。你需要一個for循環或類似下面的東西。

我相信這會工作:

int temp[9]; 
memcpy(temp, logic[2], sizeof(temp)); 

但是我一般建議使用std::vectorstd::array代替。

4

除了陣列衰減到一個指針,也可以將其綁定到的引用:本

int (&temp)[9] = logic[2]; 

一個優點是它可以讓你使用它C++ 11範圍基於for循環:

for (auto t : temp) { 
    // stuff 
}