2014-10-27 51 views
0

我想使數組的功能打印2列3列和3行。我不知道事情是如何使程序從用戶獲取輸入並傳送到功能上的這一部分:如何調用數組的成員?

array<array<int, columns>,rows>c[item]; 
cout<<"2-D Array print: "<<endl; 

我一直想弄明白,我不似乎去。任何地方:(請我需要幫助

#include <iostream> 
#include <array> 
#include <iomanip> 

using namespace std; 

const size_t rows=3; 
const size_t columns=3; 
void printArray(const array<array<int, columns>,rows>&); 

int main(){ 
    const size_t arraysize=9; 
    array<int, arraysize>c; 

    cout<<"Enter an array of 9 floats: "<<endl; 

    for (size_t i=0;i<c.size(); i++) { 
     cin>>c[i]; 
    } 
    cout<<endl; 

    cout<<"Normal array print: "; 
    for (int item :c) { 
     cout<<item<<" "; 
    } 

    array<array<int, columns>,rows>c[item]; 
    cout<<"2-D Array print: "<<endl; 
} 

void printArray(const array<array<int, columns>,rows>&a){ 
    for(auto const &row:a) 
    { 
     for(auto const &element:row) 
      cout<<element<<" "; 
      cout<<endl; 
    } 
} 
+0

那麼你的問題是什麼?你是否收到編譯錯誤?意外/不正確的行爲?順便說一句,你的代碼是C++,所以我不知道你爲什麼要使用CSS代碼片斷進行格式化,這不適用於C++代碼。 – CoryKramer 2014-10-27 12:05:29

+0

我很抱歉,我對此很陌生,我不知道如何格式化它。 是的,當我編譯它時,我得到在這部分的錯誤 array <數組<行,列>,行> c [item]; 具體到它的最後部分,c [item]; – Meeeeee 2014-10-27 12:08:37

回答

0

(既然你已經在打印點的數據,我解釋的問題爲:我不知道如何將數組轉換爲傳遞到功能)

除了std::array是連續的內存存儲,並且您可以使用像uberhack以下(不能保證工作):

printArray(reinterpret_cast<const array<array<int, columns>, rows>&>(c)); 

我會感到安全多了,如果你使用的轉換回路,保證數據的一致性:

array<array<int, columns>, rows> printArr; 
for (int x = 0; x < rows; ++x) { 
    for (int y = 0; y < columns; ++y) { 
     printArr[x][y] = c[x*columns + y]; 
    } 
} 
printArray(printArr); 

輸出:

Enter an array of 9 integers: 

Normal array print: 1 2 3 4 5 6 7 8 9 2-D Array print: 
1 2 3 
4 5 6 
7 8 9 

Live Example

+0

LOL我們發佈了兩種不同的解決方案,不確定哪一個OP需要,看來我必須刪除我的:D – P0W 2014-10-27 12:13:43

+0

現在言之過早!如果帖子足夠清晰,我們將只有一個:/ – 2014-10-27 12:14:21

+0

我試了兩次,他們的工作。非常感謝你!如果我在未來發帖,我會盡量讓我的帖子更清晰。我仍然在學習如何使用這個頁面。再次感謝你。 – Meeeeee 2014-10-27 12:24:01

相關問題