C++ 在抛出';std::超出范围';what():vector::_M_range_check:__n(即8)>;=这->;size()(即8)

C++ 在抛出';std::超出范围';what():vector::_M_range_check:__n(即8)>;=这->;size()(即8),c++,C++,我试图解决一个汽车加油问题,以确定最低加油次数。程序在运行时抛出上述错误 这是我的代码: #include <iostream> #include <vector> using std::cin; using std::cout; using std::vector; using std::max; int compute_min_refills(int dist, int tank, vector<int> &stops) { int n

我试图解决一个汽车加油问题,以确定最低加油次数。程序在运行时抛出上述错误

这是我的代码:

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::vector;
using std::max;

int compute_min_refills(int dist, int tank, vector<int> &stops) {
    int num_refills{} , current_refill{} , last_refill{};

    while( current_refill <= stops.size()){
        last_refill = current_refill;

        while( current_refill <= stops.size() && ((stops.at(current_refill + 1) - stops.at(last_refill )) <= dist)){
            current_refill += 1;
        }
        if (current_refill == last_refill)
            return -1;
        if (current_refill <= stops.size())
            num_refills += 1; 
    }
    return num_refills ;
}


int main() {
    int d = 0; //dist
    cin >> d;
    int m = 0; //tank
    cin >> m;
    int n = 0; //no. of stops
    cin >> n;

    int v{};
    vector<int> stops(n,0);
    for (size_t i = 0; i < n; ++i){
    cin>> v;
    stops.push_back(v);
    }
    cout << compute_min_refills(d, m, stops) << "\n";

    return 0;
}
#包括
#包括
使用std::cin;
使用std::cout;
使用std::vector;
使用std::max;
整数计算最小值重新填充(整数距离、整数油箱、矢量和停止){
int num_refills{},当前_refill{},最后一次_refill{};
而(当前);
int n=0;//停止次数
cin>>n;
int v{};
向量停止(n,0);
对于(尺寸i=0;i>v;
停止。向后推(v);
}

cout
current\u refill有效索引从
0
size-1
。投票以键入方式关闭感谢,我意识到我应该使用while(current\u refill注意,您在
中使用
,这很好,因此您得到了一个可读性很好的运行时错误(isntead为segfault,或者更糟糕的是,没有运行时错误,只是胡言乱语的结果),你只是错过了下一步