Stl::vector erase element

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

this is a useful approach:

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

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.