获取向量的最后一个元素

时间:2014-11-13 20:02:18

标签: c++ object vector return

我的班级.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");
}

getLastPatient()应返回最后一个元素或最后添加到向量

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

但是getLastPatient()无法正常工作,程序会在执行时崩溃。

cout << h.getDoctorAt(2) << endl; // ok!
cout << h.getLastPatient() << endl; // crashes program

任何想法为什么?不想发布完整代码,很长时间。

1 个答案:

答案 0 :(得分:6)

大概你的patients向量是空的。在空容器上调用back()会导致未定义的行为。

相关问题