简体   繁体   English

调试断言失败。 Expression Map迭代器不可取消

[英]Debug Assertion Failed. Expression Map iterator not dereferencable

I'm trying to delete objects through an iterator as shown in the code below. 我正在尝试通过迭代器删除对象,如下面的代码所示。 The program seemed to run fine on ubuntu but I'm now in visual studio and it's throwing a debug assertion failed error. 该程序似乎可以在ubuntu上正常运行,但是我现在在Visual Studio中,它会引发调试断言失败错误。 Expression: Map/set iterator not dereferencable. 表达式:映射/集合迭代器不可引用。

Any help would be much appreciated. 任何帮助将非常感激。

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));
}

OK, now that the code has completely changed from what was originally posted... 好了,现在该代码已经完全脱离了最初的发布改变了... ...

The error is easy to spot. 该错误很容易发现。 You're erasing the element from the map which invalidates the iterator, then you're trying to use that iterator. 您正在从map删除使迭代器无效的元素,然后尝试使用该迭代器。 You should make a temporary copy of the pointer you need to delete before you erase the iterator, or just rearrange and do the delete first. 在擦除迭代器之前,应该对需要delete的指针进行临时复制,或者只是重新排列并首先进行delete

Also as suggested in the comments, you need to make sure that the iterator returned by find is valid, ie not equal to end() . 另外,正如注释中所建议的那样,您需要确保find返回的迭代器是有效的,即不等于end()

map<string, Booking*>::iterator it = bookings.find(flightNumber);
if (it != bookings.end())
{
    Booking* temp = it->second;
    bookings.erase(it);
    delete temp;
}

or 要么

map<string, Booking*>::iterator it = bookings.find(flightNumber);
if (it != bookings.end())
{
    delete it->second;
    bookings.erase(it);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM