简体   繁体   中英

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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