c++vectorundefined-behaviorsubscript-operator

why my code is unable to handle large array input(>10000)?


int n;//input size of array
cin >> n;
vector <int> a(n);
vector <int> in;

for (int i = 0; i < n; i++)
    cin >> a[i];//input array elements
if (n == 1) {
    cout << "1" << "\n";
    return 0;
}

for (int i = 1; i <= n ; i++)//to get longest incresing subsequence in the array
{
    int flag = 0, j = i;

    while (j < n && a[j] >= a[j - 1] ) {
        j++;
        flag = 1;
    }
    if (flag == 1) {
        in.push_back(j - i + 1);
        i = j;
    }
}

int maxval = in[0]; //to get maximum sized element from in 
for (int i = 1; i < in.size(); i++)
    if (in[i] > maxval)
        maxval = in[i];
cout << maxval << "\n";

I tried the same code for values < 10000 it's working fine...i've replaced all int's by long long int's then also it's showing vector subscript out of range error...

Sample input :

10

49532 49472 49426 49362 49324 49247 49165 49162 49108 49093

i'm expecting 0 but it shows "vector subscript out of range"


Solution

  • The reason of the problem is this statement

    int maxval = in[0];//to get maximum sized element from in 
    

    The vector in is empty when this input is used

    10
    
    49532 49472 49426 49362 49324 49247 49165 49162 49108 49093
    

    So you may not use the subscript operator.

    You could write for example

    int maxval = in.empty() ? 0 : in[0];