terminate called after throwing an instance of 'std::out_of_range'

前端 未结 2 2026
傲寒
傲寒 2021-02-10 05:08

Why does this happen my program says that it has no errors but then when I run it I get terminate called after throwing an instance of \'std::out_of_range\' what(): vector:_M_ra

2条回答
  •  心在旅途
    2021-02-10 05:54

    It looks to me as if this is due to a typo, and you should use the variable 'j' in the second loop. After the first loop,

    for (i = 0; i < 52; i++)
    {
        nums.push_back(i);
    }
    

    the variable 'i' contains the value 52, so it sounds expected that calling nums.at(i) would throw a std::out_of_range, since nums only contains 52 values, starting at index 0.

    for(int j = 0; j < 52; j++)
    {
        cout << nums.at(i) << "\n";
    }
    

    Fix it by replacing the argument of at() with 'j', which I assume was the original intent:

    for(int j = 0; j < 52; j++)
    {
        cout << nums.at(j) << "\n";
    }
    

提交回复
热议问题