Question:
While using vectors to represent a 2D matrix, an error occurs when attempting to read user input and append it to the matrix. The code below triggers a "subscript out of range" error.
<code class="cpp">vector<vector<int>> matrix; for (int i = 0; i < RR; i++) { for (int j = 0; j < CC; j++) { cout << "Enter the number for Matrix 1"; cin >> matrix[i][j]; } }</code>
Answer:
The error occurs because the vector of vectors has not been initialized with appropriate sizes before accessing its elements. To resolve this, initialize the matrix as follows:
<code class="cpp">vector<vector<int>> matrix(RR, vector<int>(CC));</code>
This code creates a matrix of RR rows and CC columns, where each cell is initialized to 0. Now, the code can access and manipulate the matrix without encountering the "subscript out of range" error.
The above is the detailed content of Why am I getting a 'subscript out of range' error when reading user input into a vector of vectors representing a 2D matrix?. For more information, please follow other related articles on the PHP Chinese website!