我正在尝试通过迭代器删除对象,如下面的代码所示。该程序似乎在 ubuntu 上运行良好,但我现在在 visual studio 中,它抛出调试断言失败错误。表达式:映射/设置迭代器不可取消引用。
如有任何帮助,我们将不胜感激。
map<string, Booking*> bookings; // private variable
/**
* remove a booking from the passenger's booking map.
* @param flightNumber string& - flight number of the booking to be removed.
*/
void Passenger::removeBooking(string& flightNumber)
{
map<string, Booking*>::iterator it = bookings.find(flightNumber);
bookings.erase(it);
delete (*it).second; // <-- error occurs here
}
/**
* add a booking to the passenger's booking map.
* @param booking Booking& - the booking to be added.
*/
void Passenger::addBooking(Booking& booking)
{
Booking* bookingPtr = new Booking(booking);
bookings.insert(pair<string, Booking*>(booking.getFlightNumber(), bookingPtr));
}
/**
* add a booking to the passenger's booking map.
* @param flightNumber string& - flight number of the booking.
* @param seat Seat::Type - seat type of the booking.
* @param status Booking::Type - status of the booking.
*/
void Passenger::addBooking(string& flightNumber, Seat::Type seat, BookingStatus::Type status)
{
Booking *bookingPtr = new Booking(flightNumber, seat, status);
bookings.insert(pair<string, Booking*>(flightNumber, bookingPtr));
}
最佳答案
好的,现在代码已经完全从最初发布的代码改变...
错误很容易被发现。您正在从 map
中删除使迭代器无效的元素,然后您正在尝试使用该迭代器。在删除迭代器之前,您应该制作一份需要delete
的指针的临时拷贝,或者只是重新排列并先执行delete
。
另外,正如评论中所建议的,您需要确保 find
返回的迭代器是有效的,即不等于 end()
。
map<string, Booking*>::iterator it = bookings.find(flightNumber);
if (it != bookings.end())
{
Booking* temp = it->second;
bookings.erase(it);
delete temp;
}
或
map<string, Booking*>::iterator it = bookings.find(flightNumber);
if (it != bookings.end())
{
delete it->second;
bookings.erase(it);
}
关于c++ - 调试断言失败。表达式映射迭代器不可取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532193/