简体   繁体   中英

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 (ie 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!

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);

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM