Problem with vector function in C++

Asked

Viewed 292 times

0

Hello, I’m trying to make a matrix calculator and my idea would be that the user entered with the number of rows, columns and soon after with the matrix elements, the problem is that when I write the elements the program gives input stream error, if someone can help me.

SOURCE

#include<iostream>
#include<stdio.h>
#include<vector>

using namespace std;

int main()
{
    int opc;
    int L = 0; //linha
    int C = 0; // coluna
    vector<vector<int>> mat1(L, std::vector<int>(C));
    vector<vector<int>> mat2(L, std::vector<int>(C));
    vector<vector<int>> matResp(L, std::vector<int>(C));

    cout << "1-Sum\n0-Exit\n";
    cin >> opc;

    system("cls");

    switch (opc)
    {
    case 1:
        //soma
        cout << "Enter with number of Lines:\n";
        cin >> L;
        cout << "Enter with number of Coluns:\n";
        cin >> C;

        cout << "Write the elements of Matrix A:\n";

        for (int i = 0; i < L; i++)
        {
            for (int j = 0; j < C; j++)
            {
                cin >> mat1[i][j];
            }
        }

        system("cls");

        cout << "Write the elements of Matrix B:\n";
        for (int i = 0; i < L; i++)
        {
            for (int j = 0; j < C; j++)
            {
                cin >> mat2[i][j];
            }
        }

        system("cls");

        for (int i = 0; i < L; i++)
        {
            for (int j = 0; j < C; j++)
            {
                matResp[i][j] = mat1[i][j] + mat2[i][j];
            }
        }

        for (int i = 0; i < L; i++)
        {
            for (int j = 0; j < C; j++)
            {
                cout << "[ " << matResp[L][C] << " ]";

                if (j == 2)
                    cout << endl;
            }
        }

        cout << endl;

        break;

    case 0:
        break;

    default:
        cout << "Wrong option";
        return main();
    }
}

1 answer

1


You are creating the vectors before requesting the size, that is, with 0 rows and 0 columns.

  • Hmm ok I’ll check it out and as soon as I can I’ll back up

  • agreed to find the error obliged... the question would be to put a Max number in the variables L and C and of course to change them to const

  • @Leonardov.Degasperin and Edson, can you improve this answer? As it seems to me a comment and not a solution with example of correction. So it would be more useful to those who might have the same problem. Say when it’s edited to delete my comment.

  • @Sergio keep in mind the following, instead of me initializing the variables C and L in 0 I weight the user type the array order

Browser other questions tagged

You are not signed in. Login or sign up in order to post.