Home>
Question

joi's 10th Japan Information Olympic Qualifying D-1st grade (A First Grader)
I'm doing the problem
The following code causes an error when executed in Visual Studio
However, if you try it with joi's code test (gcc) etc., it can be executed normally

What is the cause?

code
#include 
#include<iostream>
#include<vector>
#include<string>
#include<stack>
#include<list>
#include<cmath>
#include<ctime>
#include<cstdio>
using namespace std;
typedef unsigned long long int ulli;
typedef long long int lli;
int add (int);
int main () {
    int n;cin >>n;
    vector<int>v;
    for (int i = 0;i<n;i ++) {
        int t;cin >>t;
        v.push_back (t);
    }
    int Aend = v [n -1];
    v.pop_back ();
    vector<vector<ulli >>dp (22, vector<ulli>(n, 0));
    dp [v [0]] [0] ++;
    for (int i = 0;i<n -1;i ++) {
        for (int j = 0;j<= 20;j ++) {
            if (dp [j] [i]! = 0) {
                int Mx = j + v [i + 1];
                int Mn = j --v [i + 1];
                if (add (Mx)! = 100) {
                    dp [Mx] [i + 1] + = dp [j] [i];
                }
                if (add (Mn)! = 100) {
                    dp [Mn] [i + 1] + = dp [j] [i];
                }
            }
        }
    }
    cout<<dp [Aend] [n --2]<<endl;
    return 0;
}
int add (int m) {
    if (0>m || m>20) m = 100;
    return m;
}
error
  • Answer # 1

    vectorvIs out of range access.

      vector<int>v;
        for (int i = 0;i<n;i ++) {
            int t;cin >>t;
            v.push_back (t);
        }
        int Aend = v [n -1];
        v.pop_back ();// Since one is removed from the end here, the number of elements is n-1, that is, the index is valid from 0 to n-2.
    (Omitted)
        for (int i = 0;i<n -1;i ++) {
            for (int j = 0;j<= 20;j ++) {
                if (dp [j] [i]! = 0) {
                    int Mx = j + v [i + 1];// When i is n-2, v [n-1], that is, accessing out of range

    vectorofoperator []Isat ()Unlike, the range check is not specified, and it is undefined behavior when accessing after the number of elements.
    In the vector implementation that comes with Visual C ++, when building Debugoperator []Since the range is also checked, the Debug Assert is displayed.

      _NODISCARD const _Ty&operator [] (const size_type _Pos) const
            {// subscript nonmutable sequence
     #if _ITERATOR_DEBUG_LEVEL! = 0
            _STL_VERIFY (_Pos<size (), "vector subscript out of range");
     #endif/* _ITERATOR_DEBUG_LEVEL! = 0 * /
            return (this->_Myfirst () [_Pos]);
            }

    However, if you try it with joi's code test (gcc) etc., it can be executed normally

    It just happens to move.