2013-11-10 136 views
2

我在教自己C++並從教科書中解決問題。到目前爲止,我已經介紹了諸如數據類型,聲明,顯示,賦值,交互式輸入,選擇(if-else)和重複(for/while循環...),函數和數組等基本知識。我還沒有對指針什麼,但我知道他們是什麼...從C++函數返回數組

我碰到這個問題就來了:

到真僞檢驗的答案如下:TTFF T.給定二維答案數組,其中每行對應於在一個測試中提供的答案,編寫一個接受二維數組和測試次數作爲參數的函數,並返回一個包含每個測試成績的一維數組。 (每題5分,從而最大可能的等級爲25)具有以下數據測試你的函數:

enter image description here

我的理解是,C++函數不能返回數組 - 至少,這是我在這個論壇上的其他帖子上閱讀的內容。它是否正確?如果是這樣,他們如何期待你做這個問題,因爲我還沒有指出。我認爲可能的唯一的另一種方式是通過引用來傳遞數組......但問題詞幹只說有2個參數給函數,所以我想也許這種方法被排除了。該方法將需要第三個參數,它是您修改的數組,因此它會隱式返回。

我有一些代碼,但它不正確(只有我的calcgrade功能需要工作),我不知道如何前進。請有人請指教?謝謝!!

#include<iostream> 

// Globals 
const int NROW = 6, NCOL = 5; 
bool answers[NCOL] = {1, 1, 0, 0, 1}; 
bool tests[][NCOL] = {1, 0, 1, 1, 1, 
         1, 1, 1, 1, 1, 
         1, 1, 0, 0, 1, 
         0, 1, 0, 0, 0, 
         0, 0, 0, 0, 0, 
         1, 1, 0, 1, 0}; 
int grade[NROW] = {0}; 

// Function Proto-Types 
void display1(bool []); 
void display2(bool [][NCOL]); 
int calcgrade(bool [][NCOL], int NROW); 


int main() 
{ 


    calcgrade(tests, NROW); 
    display2(tests); 

    return 0; 
} 

// Prints a 1D array 
void display1(bool answers[]) 
{ 
    // Display array of NCOL 
    for(int i = 0; i < NCOL; i++) 
     std::cout << std::boolalpha << answers[i] << std::endl; 
    return; 
} 

// Print 2d Array 
void display2(bool answers[][NCOL]) 
{ 
    // Display matrix: 6x5 
    for(int i = 0; i < NROW; i++) 
    { 
     for(int j= 0; j < NCOL; j++) 
     { 
      std::cout << std::boolalpha << answers[i][j] << std::endl; 
     } 
     std::cout << std::endl; 
    } 

    return; 
} 

int calcgrade(bool tests[][NCOL], int NROW) 
{ 

    for(int i = 0; i < NROW; i++) 
    { 
     for(int j = 0; j < NROW; j++) 
     { 
      if(tests[i][j]==answers[j]) 
       grade[i] += 5; 
     } 
     printf("grade[%i] = %i", i, grade[i]); 
    } 

    return grade; 
} 
+2

正確的答案是返回一個'VECTOR'。如果你的教科書正在教你關於數組而不是'vector's,作者不應該被允許再次寫。 –

+0

我的書甚至不會談論矢量......( – user1527227

+0

)如果你有一本C++書籍,其中沒有章節涵蓋C++標準庫,並且在'std :: vector <>'的情況下,可以說這個庫在所有現代C++程序中使用最多的類型,你需要另外一本書(並且作者需要不同的職業) – WhozCraig

回答

1

嘗試使用std::vector

向量是序列容器,表示可以改變大小的數組。

你可以這樣做:

vector<bool> function() 
{ 
    vector<bool> vec; 

    vec.push_back(true); 
    vec.push_back(false); 
    vec.push_back(true); 

    return vec; 
} 
0

您可以:

  • 如你所說,返回指向動態分配的數組,
  • 你可以用字struct包括靜態數組結構類型,瞭解更多關於C++ Reference和返回/作爲你的類型的參數結構。
+0

謝謝你,我想知道是否有任何其他方法可以提供你提到的方法,因爲我還沒有涉及到那些主題,我只是想看看我是否錯過了什麼已閱讀至今... – user1527227

1

如果傳遞的測試,第二個參數的數量,這意味着你實際上知道測試次數,所以你不需要使用vector。您可以返回一個動態分配的數組(使用newmalloc)。

的代碼應該是這樣的:

int* calcgrade(bool tests[][NCOL], int NROW){ 
    int* array = new int[NROW]; 
    for(int i=0;i<NROW;i++) 
    array[i] = calculatedGrade; 
    return array; 
} 
0

這樣做將是你的主函數來創建應答數組,然後通過它與T/F陣列的分級功能一起的另一種方式。然後,你的評分函數可以在Answer數組上運行,甚至不需要返回任何東西。從本質上講,當你在函數中傳遞數組時,實際上是將指針傳遞給數組,因此你可以對它們進行操作,就好像它們通過引用傳遞一樣(它們是)。

半僞例如:

void getGrades(const int answerVector, int gradeVector) { 
    // code that computes grades and stores them in gradeVector 
}