struct初始化数组

时间:2012-01-08 08:06:27

标签: c++ arrays vector struct

typedef struct { double x, y; } vec;
typedef struct { int n; vec* v; } polygon_t, *polygon;

#define BIN_V(op, xx, yy) vec v##op(vec a, vec b) { \
    vec c; c.x = xx; c.y = yy; return c; }

#define BIN_S(op, r) double v##op(vec a, vec b) { return r; }

BIN_V(sub, a.x - b.x, a.y - b.y);
BIN_V(add, a.x + b.x, a.y + b.y);
BIN_S(dot, a.x * b.x + a.y * b.y);
BIN_S(cross, a.x * b.y - a.y * b.x);

vec testPoints[] = {
                    {1, 1},
                    {3, 3},
                    {3, 5},
                    {5, 2},
                    {6, 3},
                    {7, 4}
                   };

最后的结构数组是什么?我不太明白{1, 1}如何成为一名兽医。

如果我想拥有vector<vec> allPoints,我怎样才能将vec推入此向量?这不起作用allPoints.push_back({1, 2});以及allPoints.push_back(new vec(1, 2));

2 个答案:

答案 0 :(得分:4)

{}是初始化程序,并且:

vec v = { 2, 3 };

相当于:

vec v;
v.x = 2;
v.y = 4;

对于数组:

int myints[3] = { 1, 2, 3 };

会初始化数组中的元素:

myints[0] = 1;
myints[1] = 2;
myints[2] = 3;

对于结构数组:

vec mystructs[2] = { { 1, 2}, { 2, 3} };

初始化结构数组:

mystructs[0].x = 1;
mystructs[0].y = 2;
mystructs[1].x = 2;
mystructs[1].y = 3;

以您表达的方式使用std::vector<vec>将构造函数添加到vec结构中:

struct vec
{
    vec(double a_x, double a_y) : x(a_x), y(a_y) {}
    double x,y;
};

std::vector<vec> allPoints;

allPoints.push_back(vec(1,2));

答案 1 :(得分:2)

动态构造类C结构在C ++ 2003中不起作用。它适用于C ++ 2011:

std::vector<vec> v;
v.push_back(vec{ 1, 2 });

如果需要在C ++ 2003中创建std::vector<vec>,最好的方法可能是创建辅助函数来初始化对象

vec make_vec(double a, double b) {
    vec v = { a, b };
    return v;
}
...
v.push_back(make_vec(1, 2));