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}如何成为vec。

如果我想要vector<vec> allPoints,如何将vec推入该 vector ?这不起作用allPoints.push_back({1, 2});以及allPoints.push_back(new vec(1, 2));

最佳答案

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

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

关于c++ - 结构初始化数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8776189/

10-15 04:41