Home  >  Article  >  Backend Development  >  Why Am I Getting \'Subscript Out of Range\' Errors When Creating a Matrix Using Vectors?

Why Am I Getting \'Subscript Out of Range\' Errors When Creating a Matrix Using Vectors?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 14:58:30398browse

Why Am I Getting

Vector of Vectors to Create Matrix

In an attempt to create a 2D matrix using vectors (vectors of vectors), a user encountered "subscript out of range" errors while appending data to the matrix using the following code:

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

The error occurs because the vectors are not initialized before being accessed. You can resolve this issue by initializing the vector of vectors to the correct size before accessing any elements. This can be done as follows:

<code class="cpp">vector<vector<int>> matrix(RR, vector<int>(CC));</code>

This line of code creates a vector of size RR, where each vector is of size CC, and initializes all elements to 0.

The above is the detailed content of Why Am I Getting \'Subscript Out of Range\' Errors When Creating a Matrix Using Vectors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn