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

1.1k views Asked by At
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"

2

There are 2 answers

1
Vlad from Moscow On BEST ANSWER

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];
6
Ahmed Anter On

Fix this:

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

the vector class operator checks the index is between lower and upper limit of array which will be (0 -> size-1)

MSVC lib:

    _NODISCARD _Ty& operator[](const size_type _Pos) noexcept { // strengthened
        auto& _My_data = _Mypair._Myval2;
#if _CONTAINER_DEBUG_LEVEL > 0
        _STL_VERIFY(
            _Pos < static_cast<size_type>(_My_data._Mylast - _My_data._Myfirst), "vector subscript out of range");
#endif // _CONTAINER_DEBUG_LEVEL > 0

        return _My_data._Myfirst[_Pos];
    }

the problem is that the in.push_back never get called then the size is zero.

so in[0] call operator will throw exception index out range.