Home > Article > Backend Development > How to Avoid Subscript Out of Range Errors When Creating a 2D Matrix Using Vectors of Vectors?
Vector of Vectors for Matrix Creation: Overcoming Subscript Out of Range Errors
When attempting to create a 2D matrix using vectors of vectors, it's crucial to initialize the data structure correctly to avoid subscript out of range errors. This issue occurs when trying to access elements of a vector without first allocating the necessary memory.
Resolving the Issue
To resolve this issue, you must initialize the vector of vectors to the appropriate size before accessing any elements. This can be achieved using the following code:
<code class="cpp">vector<vector<int>> matrix(RR, vector<int>(CC));</code>
This code creates a vector of size RR initialized with CC vectors, each filled with 0. Now, you can safely access elements within the matrix vector using the following syntax:
<code class="cpp">matrix[i][j] = user_input;</code>
Example Usage
Consider the example code you provided:
<code class="cpp">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>
By initializing matrix using the method described above, you can now safely populate the matrix with user input using the loop. The subscript out of range error will no longer occur because you have allocated the necessary memory for the matrix.
The above is the detailed content of How to Avoid Subscript Out of Range Errors When Creating a 2D Matrix Using Vectors of Vectors?. For more information, please follow other related articles on the PHP Chinese website!