JJ Liu
JJ Liu

Reputation: 1421

Array of struct initialization

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

What does the array of structs at last work? I don't quite understand how {1, 1} become a vec.

If I want to have a vector<vec> allPoints, how can I push a vec into this vector? This doesn't work allPoints.push_back({1, 2});, as well as allPoints.push_back(new vec(1, 2));

Upvotes: 2

Views: 2410

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154025

Constructing C-like structs on the fly doesn't work in C++2003. It works in C++2011:

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

If you need to create a std::vector<vec> in C++2003 the best way is probably to create a helper function to initialize your objects

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

Upvotes: 2

hmjd
hmjd

Reputation: 122001

The {} is an initializer and:

vec v = { 2, 3 };

is equivalent to:

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

For an array:

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

would initialise the elements in the array:

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

For an array of structs:

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

initialises the array of structs:

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

To use a std::vector<vec> in the manner you expressed add a constructor to the vec struct:

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

Upvotes: 4

Related Questions