-1

Why am I getting this error on executing my code? In it I am trying to implement an adjacency list for a graph.

#include <iostream>
#include<vector>

#include<stdio.h>

using namespace std;

int main()
{
    int t;

    cin >> t;
    while(t--)
    {
        int n,k,i,m=0;
        cin >> n;
        vector<int> mv[n];
        for(i=0;i<n;i++)
        {
            for(m=0;m<n;m++)
            {
                scanf("%d",&k);
                if(k>0)
                    mv[i].push_back(k);
            }
        }
        cout << mv[0].at(0) << " ";
        cout << mv[0].at(1) << " ";
        cout << mv[0].at(2) << " ";
        cout << mv[1].at(1) << " ";
        cout << mv[2].at(1) << " ";
        cout << mv[3].at(0) << " ";
    }
    return 0;
}
jpo38
  • 20,821
  • 10
  • 70
  • 151
Mrinal Verma
  • 349
  • 2
  • 6
  • 14
  • Please take [the tour](http://stackoverflow.com/tour) and read the [help page](http://stackoverflow.com/help). Here is a nice list of [C++ books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). –  Jan 04 '17 at 14:32
  • What inputs lead to the crash? (what values of `t`, `n` and `k`s...)? – jpo38 Jan 04 '17 at 14:39
  • 1
    What values did you enter? For example, if `n` is 1, `mv[0].at(2)` will throw, – Bo Persson Jan 04 '17 at 14:39

1 Answers1

2

You iterate through elements without making sure you're in your vectors bounds...

Replace

cout << mv[0].at(0) << " ";
cout << mv[0].at(1) << " ";
cout << mv[0].at(2) << " ";
cout << mv[1].at(1) << " ";
cout << mv[2].at(1) << " ";
cout << mv[3].at(0) << " ";

By:

for(i=0;i<n;i++)
{
    for ( size_t pos = 0; pos != mv[i].size(); ++pos )
        cout << mv[i].at(pos) << " ";
}

and it should work better then...

jpo38
  • 20,821
  • 10
  • 70
  • 151