confused
confused

Reputation: 761

Are you not allowed to erase a vector element from an instantiated vector?

Is it not possible to erase a vector element when I have declared it in my function instead of building it?

I have tried the code below but it crashes my app at if I leave the erase in (with only a vague stack trace as output). If I remove it all is fine. I thought I understood the right way to use erase but evidently I do not :)

model_points.begin should give me the start of the vector and the +i is in the 0-13 range so any of those should be valid elements. Unless I can't erase begin + 0, but I thought you could.

  std::vector<cv::Point2d> image_points;

  std::vector<cv::Point3d> model_points {
                                                  {0, 0.01, -0.01},
                                                  {0.001, 0.001, -0.001},
                                                  {-0.01, -0.001, 0.01},
                                                  {-0.09, -0.1, 0.7},
                                                  {-0.006, 0.09, 0.68},
                                                  {0.09, -0.42, 0.01},
                                                  {0.07, -0.15, 0.1},
                                                  {0.1, 0.7, 0.64},
                                                  {-0.8, 0.01, 0.94},
                                                  {-0.02, 0.4, 0.11},
                                                  {-0.05, 0.02, 0.18},
                                                  {0.07, 0.01, 0.08},
                                                  {0.0, 0.02, 0.11},
                                                  {0.06, 0.03, 0.11}
                                                };


  for(int i = 0; i < 14; i++) {
    if(hotpoints[i].x != 0.0 && hotpoints[i].y != 0.0){
      cv::Point2d p(hotpoints[i].x, hotpoints[i].y);
      image_points.push_back(p);
    }else{
      //we have skipped this one in image points so we
      //need to remove it from model points
      model_points.erase(model_points.begin() + i);
    }
  }

Upvotes: 0

Views: 36

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51825

Your for (int i = 0; i < 14; i++) assumes that the vector has a fixed size of 14 elements. However, each time you call erase, you are reducing the size, and a later attempt to access element 13 (say) will be attempting to access an out-of-bounds element.

So, make your loop look something like this:

for (size_t i = 0; i < model_points.size(); i++) {
    //...

Upvotes: 3

Related Questions