簡體   English   中英

stdvector插入和擦除問題

[英]stdvector inserting and erasing problem

我需要控制應用程序中接觸點的數量,為此,我使用了矢量容器,而我的基本設置是:

//--------------------------------------------------------------
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;
    }
}

但是,當我向上移動手指時,應用程序凍結,因此touchUp()中大多數出現問題,有什么想法嗎?

很多事情:首先,您不能修改(擦除/插入)容器,並且期望迭代器保持有效!

讓我們來看看。 我也想修改touchMove

void testApp::touchMoved(const ofTouchEventArgs & touch)
{
  if (touch.id < touchPoints.size())
    touchPoints[touch.id] = ofVec2f(touch.x, touch.y);
}

接下來,大一點:

void testApp::touchUp(const ofTouchEventArgs & touch)
{
  if (touch.id < touchPoints.size())
    touchPoints.erase(touchPoints.begin() + touch.id);
}

基本上touch.id 只是在載體的指數,所以我們可以直接使用。 要從中間擦除一個元素,我們只需在相應的迭代器上調用“ erase ”即可。 由於vector具有隨機訪問迭代器,因此可以在恆定時間內說begin() + touch.id

更新:實際上我認為您的代碼已損壞:從向量中刪除一個元素后,其他元素將向上移動,因此您將失去touch.id與容器元素之間的關聯! 您猜到了,需要一個關聯的容器:

struct testApp
{
  std::map<int, ofVec2f> touchPoints;
  bool isTouching;

  void touchDown(const ofTouchEventArgs & touch)
  {
    isTouching = true;
    touchPoints[touch.id] = ofVec2f(touch.x, touch.y);
  }

  void touchMoved(const ofTouchEventArgs & touch)
  {
    touchPoints[touch.id] = ofVec2f(touch.x, touch.y);
  }

  void touchUp(const ofTouchEventArgs & touch)
  {
    isTouching = false;
    touchPoints.erase(touch.id);
  }
};

如果已經完成iter=touchPoints.erase(iter) ,則不應該這樣做++iter 您已經移至下一項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM