2013-11-10 138 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 
}