red_always_mafia
red_always_mafia

Reputation: 189

Issue with iterating over vector of pairs to draw lines

I am trying to draw line segments in openGL. At some point in my program, I push back standard pairs containing X and Y coordinates. I've left the code where I push the X and Y coordinates into the vector out of this post. I've placed a breakpoint and confirm that the points inside the vector are the points I expect to be inside the vector.

My issue is that the for loop, where I iterate over the vector of pairs, is behaving strangely. If i place a breakpoint in the for loop, it only ever triggers when the iterator is pointing at the final thing in the vector. If I try to print out the values with the commented out code in the for loop, only the data of the final pair in the vector ever gets printed.

It is worth noting that they X and Y axes draw with no issue. And if I look inside the vector, see the values I want, and then hardcode those values into glVertex2f, they draw properly. So the core issue is I cannot get the code inside the for loop to work. My guess is that for some reason the for loop is only happening once, so only one vertex is being sent to openGL and so no lines are drawn as a result of that for loop.

void Draw(void)
{
  // clear the screen
  glClearColor(1, 1, 1, 0);
  glClear(GL_COLOR_BUFFER_BIT);

  glColor3f(0, 0, 0);

  glBegin(GL_LINES);

  //Draws the Y Axis
  glVertex2f(0, 1);
  glVertex2f(0, -1);
  //Draws the X axis 
  glVertex2f(1, 0);
  glVertex2f(-1, 0);

  std::vector<std::pair<float, float>>::iterator it;
  for (it = vertices.begin(); it != vertices.end() - 1; ++it);
  {
    glVertex2f(it->first, it->second);
    //std::cout << "vertices.size.." << vertices.size() << std::endl; 
    //std::cout << vertices.at(i).first << " " << vertices.at(i).second << "i: " << i << std::endl;
  }

  glEnd();
  glutSwapBuffers();
}

void Loop(void) 
{
  glutPostRedisplay();
}


int main(int argc, char *argv[]) 
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
  glutInitWindowPosition(0, 0);
  glutInitWindowSize(width, height);
  glutCreateWindow(name);
  glutDisplayFunc(Draw);
  glutIdleFunc(Loop);
  Init();
  glutMainLoop();
  return 0;
}

Upvotes: 1

Views: 553

Answers (1)

basav
basav

Reputation: 1495

I tried out your code.It's strange that size is printed correctly but yet no elements are printed within loop.

Anyway, another way(not the best) but that works would be this:

 for(int i = 0;i<vertices.size();++i)
  {
    glVertex2f(vertices[i].first, vertices[i].second);
  }  

Upvotes: 1

Related Questions