c++ - Segmentation fault while iterating through and erasing some elements from std::map? -
i using several std::map
type data containers following:
std::map<int, std::vector< cv::point > > mapgoodcontours; std::map<int, ellipseproperties> ellipsepropertiesmap; std::map<int, float> m_markerradiusmap; std::map<int,cv::point2f> markers;//this part of class
i iterate through these containers , erase elements after elements meet condition shown in following code.
auto radiusmapcounter = m_markerradiusmap.begin(); auto markercounter = frames.markers.begin(); auto goodcontourscounter = mapgoodcontours.begin(); if(m_markerradiusmap.size()==ellipsepropertiesmap.size() && frames.markers.size()==ellipsepropertiesmap.size() && mapgoodcontours.size()==ellipsepropertiesmap.size()) { for(auto ellipsepropertycounter = ellipsepropertiesmap.begin(); ellipsepropertycounter != ellipsepropertiesmap.end(); ellipsepropertycounter++) { float upperlimit = (float)m_upperfactor*(float)ellipsepropertycounter->second.radius; float lowerlimit = (float)m_lowerfactor*(float)ellipsepropertycounter->second.radius; if(ellipsepropertycounter->second.mindistancefromotherellipse>upperlimit || ellipsepropertycounter->second.mindistancefromotherellipse<lowerlimit) { ellipsepropertiesmap.erase(ellipsepropertycounter); m_markerradiusmap.erase(radiusmapcounter); frames.markers.erase(markercounter); mapgoodcontours.erase(goodcontourscounter); } else { smallcontours.push_back(goodcontourscounter->second); } radiusmapcounter++; markercounter++; goodcontourscounter++; } }
i baffled find have segmentation faults shown in image. fault points line code
radiusmapcounter++;
what doing wrong?
you cannot increment iterator after erased element points container. create copy of iterator, increment it, delete element via copy.
if using c++11 or later, std::map::erase(...)
returns iterator following last removed element, can use instead of incrementing invalid one. no need create copy of iterator use in erase
in case.
for(auto ellipsepropertycounter = ellipsepropertiesmap.begin(); ellipsepropertycounter != ellipsepropertiesmap.end(); /* not increment iterator here */) { float upperlimit = (float)m_upperfactor*(float)ellipsepropertycounter->second.radius; float lowerlimit = (float)m_lowerfactor*(float)ellipsepropertycounter->second.radius; if(ellipsepropertycounter->second.mindistancefromotherellipse>upperlimit || ellipsepropertycounter->second.mindistancefromotherellipse<lowerlimit) { ellipsepropertycounter = ellipsepropertiesmap.erase(ellipsepropertycounter); radiusmapcounter = m_markerradiusmap.erase(radiusmapcounter); markercounter = frames.markers.erase(markercounter); goodcontourscounter = mapgoodcontours.erase(goodcontourscounter); } else { smallcontours.push_back(goodcontourscounter->second); radiusmapcounter++; markercounter++; goodcontourscounter++; ellipsepropertycounter++; // increment loop iterator in 'else' case } }
Comments
Post a Comment