ciso
April 4, 2014, 3:39pm
#1
hi…wich is the way to erase a specif element in a vector ? i have this situation:
for(int i=0; i<num; i++){
if((punto[i])->mouse(mouseX, mouseY)){
punto[i]-> c=125;
cout<<punto[i]<<endl;
punto.erase(punto.begin());
}else {
punto[i]-> c=255;
}
}
the aim is erase the object selected by the mouse.
thanks
zach
April 4, 2014, 5:03pm
#2
this is a useful approach:
The erase–remove idiom is a common C++ technique to eliminate elements that fulfill a certain criterion from a C++ Standard Library container. A common programming task is to remove all elements that have a certain value or fulfill a certain criterion from a collection. In C++, this could be achieved using a hand-written loop. It is, however, preferred to use an algorithm from the C++ Standard Library for such tasks.
we wrap it with ofRemove()… here’s simple example:
bool removeTest( ofPoint & a){
return a.x < 400;
}
//--------------------------------------------------------------
void testApp::setup(){
vector < ofPoint > pts;
for (int i = 0; i < 1000; i++){
pts.push_back( ofPoint(ofRandom(0,1000), ofRandom(0,1000)));
}
cout << "pts before: " << pts.size() << endl;
ofRemove(pts, removeTest);
cout << "pts after: " << pts.size() << endl;
for (int i = 0; i < pts.size(); i++){
cout << pts[i].x << endl;
}
}
the removeTest is a boolean predicate function. In your case, you might set a boolean flag after checking mouse, for example and then use that flag to return true if the object should be deleted.
the output looks like:
pts before: 1000
pts after: 569
649.419
547.525
972.753
938.259
501.367
999.823
798.144
897.113
904.025
643.411
514.18
so it remove less then half the points, all the ones which had an x value less then 400.
hope this helps!
zach
2 Likes
zach
April 4, 2014, 5:04pm
#3
ps: one reason to do it this way is that the size of the vector changes as you start removing elements, so it’s hard to write a for loop and delete elements at the same time.