AmazingVal
AmazingVal

Reputation: 301

C++ vector class to store pointers to objects

I have a Polygon class. Currently, the coordinates of the polygon are stored in a double array, where the number of rows is specified by "n", and the number of columns is just 3 (x, y, z).

I want to rewrite this using the stl vector instead (i.e. each element in the vector would be a pointer to a float array of size three). How would this be done? Like is this a valid declaration?

vector<float*> vertices;

Thanks in advance!

Upvotes: 2

Views: 2128

Answers (4)

user3287648
user3287648

Reputation: 87

vector < vector <float> (3)> (n) ; this will do the job

Upvotes: 0

concept3d
concept3d

Reputation: 2278

struct Vector3 {

 Vector3( float x, float y, float z):_x(x),_y(y),_z(z) )
 {
 }

 float _x , _y , _z;
};

std::vector<Vector3> vertices;

No need for a pointer, since it will add the complexity of managing the memory (if it was allocated by new), because std::vector won't own the pointer, and you will have to delete it.

Also std::vector is guaranteed to be contiguous in memory so it's safe to take the address of the first element,

&vertices[0]

And you can pass it to an API like openGL for example.

Adding new elements is also easy, you either create a constructor or set the elements one by one.

Example for a constructor:

vertices.push_back(Vector3( x, y, z ));

It's also a better practice to allocate your memory once at the beginning.

vertices.reserve( verticeCount);

Upvotes: 5

murrekatt
murrekatt

Reputation: 6129

With C++11 you could do this:

std::vector<std::tuple<float, float, float>> points;

if you don't have C++11, you could use boost to get tuple:

#include <boost/tuple/tuple.hpp>

std::vector<boost::tuple<float, float, float> > points;

or you could have a struct to hold your three floats:

struct Points
{
  float x_;
  float y_;
  float z_;
};

std::vector<Points> points;

Stay away from raw pointers when you don't need them. It's much safer to rely on STL containers or to define your own structs/classes to hold things.

Upvotes: 0

Hidde
Hidde

Reputation: 11921

Yes. You can also create a struct Point, which stores a 3D point and make a vector which uses the struct:

struct Point {
  double x, y, z;
}

vector<Point> points;

Use the vector as you would use it normally. You can also store pointers to points in the vector if you prefer that.

Upvotes: 0

Related Questions