C++ 有没有办法按名称访问 std::vector 元素?

C++ is there way to access a std::vector element by name?

我正在试验一个简单的顶点 class。

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

假设我们创建了一个 Vertex 对象,如下所示:

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

我想知道是否可以为向量的每个元素指定一个名称?

假设每个 std::vector 的大小都只有 3。我知道我可以通过 v0.coords[0] 到 [=17 等方式访问向量的元素或索引=]

但是,我想知道是否有一种方法可以为向量的每个元素分配一个名称,即:

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

因此,如果我要访问向量,我可以通过名称而不是索引进行访问。

这可能吗?如果是这样,我该如何创建这样的别名?

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

不,没有。至少,不是你想要的方式。

我想你可以使用宏,例如:

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

现在您可以根据需要使用 v0.coords_xv0.coords_yv0.coords_z

或者,您可以使用getter方法,例如:

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]; }
};

现在您可以根据需要使用 v0.x()v0.y()v0.z()

但实际上,在这种情况下,根本没有理由使用 vector。这只是完成这项工作的错误工具。请改用 struct,例如:

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

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

或者:

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

现在您可以根据需要使用 v0.coords.xv0.coords.yv0.coords.z