Home > Backend Development > C++ > Why am I getting a \'subscript out of range\' error when reading user input into a vector of vectors representing a 2D matrix?

Why am I getting a \'subscript out of range\' error when reading user input into a vector of vectors representing a 2D matrix?

Mary-Kate Olsen
Release: 2024-11-03 01:21:02
Original
1072 people have browsed it

Why am I getting a

Vector of Vectors for Matrix Representation

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template