Home > OS >  Getting Segmentation Fault while Inserting Elements in 2d Vector in Microsoft Visual Studio 2019
Getting Segmentation Fault while Inserting Elements in 2d Vector in Microsoft Visual Studio 2019

Time:06-13

I am writing a program in which I sum all of the elements in a 2d vector and find out whether the sum of them is 0 or not.

Getting Error which I mentioned above in the title as well as in online editor I am getting error - Segmentation Fault

#include <iostream>
#include<vector>
using namespace std;

int main()
{
    int num;
    cin >> num;
    vector<vector<int>> arr;

    for (int i = 0; i < num; i  )
    { 
        for (int j = 0; j < num; j  )
        {
            cin >> arr[i][j];
        }   
    }
    int ans = 0;
    for (int i = 0; i < num; i  )
    {
        for (int j = 0; j < num; j  )
        {
            ans = ans   arr[i][j];
        }
    }

    if (ans == 0)
        cout << "YES";
    else
        cout << "NO";

    return 0;
}

CodePudding user response:

to display something in a vector, use .at()

to make a 2d vector you have to combine 2 vectors:

vector2d.push_back(vector1)

vector2d.push_back(vector2)

now you have a 2D vector.

to add something you use push_back on vector 1 or vector 2.

to display something or use a value in the 2D vector you use vector2d.at().at()

CodePudding user response:

#include <iostream>
#include<vector>

using namespace std;

int main()
{
    //User Input
    int num {};
    cout << "Enter a Number: ";
    cin >> num;

    //Init Vector
    vector <int> V1;
    vector <int> V2;
    vector<vector<int>> V2D;

    //Instead of std:cin we use push back;
    for (int i {}; i < num; i  ){ 
        V1.push_back(i);
    }
    for (int j {}; j < num; j  ){
        V2.push_back(j);
    }

    //Now we combine the Vectors to a 2D Vector
    V2D.push_back(V1);
    V2D.push_back(V2);

    //Display Vector
    //The First Vector is .at(0) and cycles through with each iteration
    for(int i {};i<V2D.at(0).size();i  ){
        cout << V2D.at(0).at(i) << " ";
    }
    cout << endl;
    //The Second Vector is .at(1) and gets Cycled through
    for(int j {};j<V2D.at(1).size();j  ){
            cout << V2D.at(1).at(j) << " ";
        }

    //The more Vectors you add, the higher the first .at Position gets
    
    //You can mess around with my code and try to implement your idea if you like
    //if (ans == 0)
        //cout << "YES";
    //else
        //cout << "NO";

    return 0;
}

You dont have to use a total of 3 Vectors, but I find it easier to explain it like that.

  • Related