I need to erase elements from a vector based on their value, I’ve tried the idiom erase-remove_if but the condition for the item to be erased is not so simple, I’ve tried something like
map<string, TLorentzVector> map_jets
vector<pair<string,double> > jets_pt
for( vector<pair<string,double> >::iterator it1 = jets_pt.begin(); it1 != jets_pt.end(); ){
if( fabs(map_jets[it1->first].PseudoRapidity()) > 2.5 )
jets_pt.erase(it1);
but I get a segmentation violation when jets_pt has size = 1.
The whole program takes data of an experiment and loops over, the map keeps track of the name of the event and the associated variable I need, while the vector stores the string of the map and a value that I need to keep track of.
I want to delete from the vector those value which does’n satisfy a few condition
if( fabs(map_jets[it1->first].PseudoRapidity()) > 2.5 )
jets_pt.erase(it1);
if( map_jets[it->first].DeltaR(map_leps["lep1"]) < 0.4 && map_jets[it->first].DeltaR(map_leps["lep2"]) < 0.4 && map_jets[it->first].DeltaR(map_leps["lep3"]) )
jets_pt.erase(it);
if( jets_emfr[k] > 0.9 )
jets_pt.erase(it);
I assume in your real code you actually call
operator++for the iterator somewhere in the loop. However you still have the problem that erase invalidates the iterator, so you would need to doHowever the
remove_if - eraseis really a much more suitable solution hereI ould remmend something like the following:
Then you can simply use
Of course in c++0x you can simply use a lambda function:
predicate = [&](...){...};creates an functor (by means of lambda syntax), which captures all used variables by reference (somap_jets, map_leps,..., indicated by the[&]) which can be used for theremove_if.automeans that the compiler should infer the type of the variable (since we don’t have a name for the type generated by the compiler for this lambda).