I need to control the amount to touch points in my application, for this I am using a vector container and my basic setup is this:
//--------------------------------------------------------------
void testApp::touchDown(ofTouchEventArgs &touch){
isTouching = true;
touchPoints.push_back( ofVec2f( touch.x, touch.y ) );
}
//--------------------------------------------------------------
void testApp::touchMoved(ofTouchEventArgs &touch){
for ( int i = 0; i < touchPoints.size(); i++ ) {
if ( touch.id == i ) {
touchPoints[i] = ofVec2f( touch.x, touch.y );
}
}
}
//--------------------------------------------------------------
void testApp::touchUp(ofTouchEventArgs &touch){
isTouching = false;
int i = 0;
for ( vector<ofVec2f>::iterator iter = touchPoints.begin(); iter != touchPoints.end(); ) {
//int i = std::distance( touchPoints.begin(), iter );
cout << "i: " << i << endl;
if ( touch.id == i ) {
iter = touchPoints.erase( iter );
}
i++;
++iter;
}
}
But when I move up a finger the app freezes, so there most be something wrong in the touchUp(), any ideas?
Many things: First off, you cannot modify (erase/insert) a container and expect iterators to remain valid!
Let’s see. I want to modify
touchMoveas well:Next, the big one:
Basically
touch.idis just the index in the vector, so we can use that directly. To erase an element from the middle, we just calleraseon the corresponding iterator. Since vector has random access iterators, we can saybegin() + touch.idin constant time.Update: Actually I think your code is broken: After you erase an element from the vector, the other elements move up, so you will lose the association between
touch.idand the container element! What’s needed is, you guessed it, an associative container: