获取向量的最后一个元素

use*_*236 -1 c++ return vector object

我的类.cpp文件中有2个方法:

getDoctorAt() 在该位置获取int ant return元素

Doctor Hospital::getDoctorAt(const int pos) const {
    if ((pos >= 0) && (pos < implHospital->doctors.size()))
        return implHospital->doctors[pos];
    else
        throw out_of_range("Index out of bounds");
}
Run Code Online (Sandbox Code Playgroud)

getLastPatient()这应该返回或最后添加到载体中最后一个元素

Patient Hospital::getLastPatient() {
    //int pos = implHospital->patients.size()-1;
    return implHospital->patients.back();
}
Run Code Online (Sandbox Code Playgroud)

但是这getLastPatient()不起作用,如果执行程序崩溃.

cout << h.getDoctorAt(2) << endl; // ok!
cout << h.getLastPatient() << endl; // crashes program
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?不想发布完整代码,很长时间.

Bar*_*rry 6

大概你的patients矢量是空的.调用back()空容器会导致未定义的行为.