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

3
  • c++, i think it is the same, the only thing is c doesn't have vector. Commented Jan 8, 2012 at 8:09
  • 2
    No, C and C++ are not the same. Note that you don't need typedef struct in C++. Commented Jan 8, 2012 at 8:10
  • i mean, this code was originally from C, I changed to C++ just because I want to use Vector. It can compile in C++ without the vector push Commented Jan 8, 2012 at 8:12

2 Answers 2

4

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));
Sign up to request clarification or add additional context in comments.

3 Comments

that's very clear. if I don't add a constructor, I can do vec temp; temp.x = 1; temp.y=2; right?
Yes, then allPoints.push_back(temp);.
Or, vec temp = {1, 2}; allPoints.push_back(temp);.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.