简体   繁体   English

打印多维数组 C++

[英]Printing Multidimensional Array C++

How do I print out this multi-dimensional vector?如何打印出这个多维向量? I just can't figure out what to put as a condition in the inner loop in my print section in the code below.我只是无法弄清楚在下面的代码的打印部分的内部循环中放置什么作为条件。 I can't seem to figure out how to loop through the array to print grades.我似乎无法弄清楚如何遍历数组以打印成绩。 Any help would be appreciated.任何帮助,将不胜感激。

#include <iostream>

using namespace std;

int main()
{
    int course, grades;

    int** crsgrd;
    // get inputs and asign grades
    cout << "Enter number of courses: ";
    cin >> course;
    crsgrd = new int * [course];
    for (int c = 0; c < course; c++) {
        cout << "Enter number of grades: ";
        cin >> grades;
        crsgrd[c] = new int[grades];
        for(int g = 0; g < grades; g++)  {
            cout << "Enter your grade: ";
            cin >> crsgrd[c][g];
        }
    }
    // print grade report
    for(int c = 0; c < course; c++) {
        for(int g = 0; g <= ?????????; g++)
            cout << crsgrd[c][g] << " ";
        cout << endl;
    }

    // free the array
    for(int i = 0; i < course; i++)
        delete [] crsgrd[i];
    delete [] crsgrd;

    return 0;
}

g < crsgrd[c].size() 或者,如果这是某种不允许内置函数的赋值,您可以创建自己的大小函数。

You have created a 2D array, not a standard vector.您创建了一个二维数组,而不是标准向量。 Arrays do not store their length, so you have to either come up with a way to store the length or switch to another type of storage container.数组不存储它们的长度,所以你要么想办法存储长度,要么切换到另一种类型的存储容器。

Here is an example that stores the number of grades as the first element of the array for a given course:下面是一个示例,它将成绩数存储为给定课程的数组的第一个元素:

#include <iostream>

using namespace std;

int main()
{
  int course, grades;

  int** crsgrd;
  // get inputs and asign grades
  cout << "Enter number of courses: ";
  cin >> course;
  crsgrd = new int * [course];
  for (int c = 0; c < course; c++) {
    cout << "Enter number of grades: ";
    cin >> grades;
    crsgrd[c] = new int[grades + 1];  // extra cell for # of grades
    crsgrd[c][0] = grades;
    // start storing grades at cell [c][1] as the first cell has the length
    for(int g = 1; g < grades+1; g++)  {
      cout << "Enter your grade: ";
      cin >> crsgrd[c][g];
    }
  }
  // print grade report
  for(int c = 0; c < course; c++) {
    cout<< "Course #" << c+1 << " grades:" << endl;

    // use first element as limit for for loop.
    // Be sure to print one more element as we have an extra cell 
    // at the end.
    for(int g = 1; g < crsgrd[c][0] + 1; g++) 
       cout << crsgrd[c][g] << " ";
       cout << endl;
  }

  // free the array
  for(int i = 0; i < course; i++)
    delete [] crsgrd[i];
  delete [] crsgrd;

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM