I'm trying to write a data structure for a basic 3D engine, but for some reason it always crashes when I try to add an index to the polygon vector. Anyone know what may be going on? Thanks

#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <gl/glut.h>
#include <windows.h>

using namespace std;

class vertex
{
  public:
	float x, y, z;

	vertex(float xCoord = 0.0, float yCoord = 0.0, float zCoord = 0.0)
	{
		x = xCoord;
		y = yCoord;
		z = zCoord;
	}
	void printVertex()
	{
	    cout << x << " " << y << " " << z << "\n";
	}

};

class polygon
{
  public:
	  int a, b, c;

  polygon(int aVert = 0, int bVert = 0, int cVert = 0)
  {
	  a = aVert;
	  b = bVert;
	  c = cVert;
  }

  void printPolygon()
	{
	    cout << a << " " << b << " " << c << "\n";
	}

};

class model
{
  public:
	  vector<vertex> Vertex;
	  vector<polygon> Polygon;
	  vector<vertex>::iterator vIterator;
	  vector<polygon>::iterator pIterator;
 /* 
  void printModel()
  {
	  cout << "Verticies:\n";
	  for(vIterator = Vertex.begin(); vIterator != Vertex.end(); vIterator++)
	  {
		  cout << *vIterator << "\n";
	  }
	  cout << "Indicies of verticies in polygons:\n";
	  for(pIterator = Polygon.begin(); pIterator != Polygon.end(); pIterator++)
	  {
		  cout << *pIterator << "\n";
	  }
  }
*/
};

void main()
{
	float x = 0.0;
	float y = 0.0;
	float z = 0.0;
	char blar = 'y';
	while(blar != 'n')
	{
		cout << "enter an x: ";
		cin >> x;
		cout << "enter a y: ";
		cin >> y;
		cout << "enter a z: ";
		cin >> z;

		vertex v = vertex(x, y, z);
		vertex u = vertex(y, z, x);
		vertex w = vertex(z, x, y);

		polygon p = polygon(0,2,1);

		model m;
		m.Vertex.push_back(v);
		m.Vertex.push_back(u);
		m.Vertex.push_back(w);

		//polygon 0 has verts v0, v2, v1 in counterclockwise order
		m.Polygon.at(0) = p; //CRASHES HERE
		//m.Polygon[0].b = m.Vertex[2];
		//m.Polygon[0].c = m.Vertex[1];

		cout << "Your vertex: ";
		//m.printModel();
		cout << "type n to quit: ";
		cin >> blar;
	}
}

I think you forgot to push the polygon element in the vertex. first you need to push element in the vector then use vector's at (index) function.
if you want to assign, use array operator instead which returns the reference. and let you add element
like below

m.Polygon.push_back (p);
// or this way.
m.Polygon[0] = p;

Check the documentation of at(..) function which throws exception when trying to access out of bound, it doesn't insert the new element, it is just used to modify the existing one or return the const reference if used as readable member.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.