Home > Software engineering >  C is there way to access a std::vector element by name?
C is there way to access a std::vector element by name?

Time:12-04

I am experimenting with a simple vertex class.

class Vertex
{
public:
    std::vector<float> coords;
    //other functionality here - largely irrelevant 
};

And lets say we create a Vertex object as below:

Vertex v0(1.f, 5.f, 7.f);

I am wondering if there is anyway to assign a name to each element of a vector?

Let's say that each std::vector will only ever have a size of 3. I know I can access an element or index of the vector in a way such as v0.coords[0] through to v0.coords[2];

However, I am wondering if there is a way in which I could assign a name to each element of the vector, ie:

v0.coords.x == v0.coords[0];
v0.coords.y == v0.coords[1];
v0.coords.z == v0.coords[2];

So that if I was to access the vector, I could access via a name rather than an index.

Is such a thing possible? If so, how do I go about creating such aliasing?

CodePudding user response:

I am wondering if there is anyway to assign a name to each element of a vector?

No, there is not. At least, not the way you want.

I suppose you could use macros, eg:

#define coords_x coords[0]
#define coords_y coords[1]
#define coords_x coords[2]

Now you can use v0.coords_x, v0.coords_y, and v0.coords_z as needed.

Or, you can use getter methods, eg:

class Vertex
{
public:
    vector<float> coords;
    //other functionality here - largely irrelevant 

    float& x(){ return coords[0]; }
    float& y(){ return coords[1]; }
    float& z(){ return coords[2]; }
};

Now you can use v0.x(), v0.y(), and v0.z() as needed.

But really, in this situation, there is just good no reason to use a vector at all. It is simply the wrong tool for the job. Use a struct instead, eg:

struct Coords
{
    float x;
    float y;
    float z;
};

class Vertex
{
public:
    Coords coords;
    //other functionality here - largely irrelevant 
};

Alternatively:

class Vertex
{
public:
    struct
    {
        float x;
        float y;
        float z;
    } coords;
    //other functionality here - largely irrelevant 
};

Now you can use v0.coords.x, v0.coords.y, and v0.coords.z as needed.

  • Related