为什么我的代码无法处理大数组输入(> 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";

我为

样本输入:

10

49532 49472 49426 49362 49324 49247 49165 49162 49108 49093

我期望为0,但显示“向量下标超出范围”

yin3573389 回答:为什么我的代码无法处理大数组输入(> 10000)?

问题的原因是此声明

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

使用此输入时,向量in为空

10

49532 49472 49426 49362 49324 49247 49165 49162 49108 49093

因此您不能使用下标运算符。

你可以写个例子

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

解决此问题:

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

向量类运算符检查索引在数组的下限和上限之间,该上限将是(0-> size-1)

MSVC库:

    _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];
    }

问题在于in.push_back永远不会被调用,然后大小为零。

因此in [0]调用运算符将​​抛出异常索引超出范围。

本文链接:https://www.f2er.com/3122789.html

大家都在问