Boost logo

Boost Users :

Subject: [Boost-users] [multi_index] doing insert() within iteration over equal_range() result?
From: Prometheus Prometheus (prometheus__0_at_[hidden])
Date: 2008-10-23 08:55:45


Hi all,

i have the following problem:
i use multi_index like this
        std::pair<Plugins::pEvents::index::type::iterator,Plugins::pEvents::index::type::iterator> range;
range = this->events.get().equal_range(boost::make_tuple(event,condition));
while(range.first!=range.second){
    // CALL an event handler!
    this->callEventHandler(range.first); // << this shows just how it works, its not exactly my code
    ++range.first;
}

within the callEventHandler and its called functions its possible that the event handler wants to register new events which results to this:
this->events.insert(eventdata);

The problem is OR can be, that the insert modifies the indices which modify the range.first iterators and thus a ++range.first results in an invalid "next" element
this makes sense and i think most of you know this and had this problem already

Questions:
Does anyone have a good idea/solution how to solve this situation correctly so that the range i received will be valid?

i thought about using a second multi_index which holds the newly inserted events and after the WHILE it gets moved to the original events index, but this solution only moves the problem from one index to the second which helps a bit but doesnt really solve the problem, since i could miss newly inserted events

another solution i thought of is like this

range = ....equal_range(...) ;
while( range.first!=range.second ){
    Plugins::Event &ev = (Plugins::Event&)*range.first; // get first event
    if(ev.alreadycalled == false){
         ev.alreadycalled = true; // this element doesnt have an index and so it shouldnt invalidate the iterator/index (right?)
         callEventHandler();
         range= ...equal_range() ; // reinitialize the range and begin to search again!
    }
    else{
        ++range.first;
    }
}

but the above solution gets slower the more events are available

thx all
_________________________________________________________________
Explore the seven wonders of the world
http://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net