How to combine structures and vectors?

I have the next problem:
Entering coordinates of points on a plain with keyboard (as rows x,y). Replacing coordinates in vector (point - structure data type). Than calculating distance from the first point to all another points.

What I can do after creating structure of points?

1
2
3
4
  struct points{  
    float x;
    float y;
  };
Last edited on
Struct is a type definition.

std::vector<points> z; 'z' is an object, whose type is a vector of points. It has no points in it yet.

Read input. For each row append a new point to the vector.
Hi! How to add a point from structure to vector?
If you have your structure points, the easiest and most common way is to create an instance of the struct, and then use push_back to add it to the vector, e.g.:
1
2
3
4
5
6
7
8
9
10
11
12
struct points {
    float x;
    float y;
};

//...

std::vector<points> pointvec;
points p;
p.x = 5.0f;
p.y = 3.6f;
pointvec.push_back(p); // add 'p' to the vector 
Thank you very much. And what are 5.0f /* and */ 3.6f
1
2
3
4
 
points p;
p.x = 5.0f;
p.y = 3.6f;
Last edited on
Ah, adding the 'f' at the end of a number just says that it is a floating point number, rather than a double. Doesn't really make a difference, just makes things clearer for me when I'm dealing with floats rather than doubles.
OK, but I should enter coordinates with keyboard. How can I do it?
Just the same way as you would normally: Input into the structure. Do you know how you do that? Here is an example:
1
2
3
4
5
6
7
8
struct myStruct {
    float a;
};

// ...

myStruct s;
std::cin >> s.a;
http://www.cplusplus.com/articles/386AC542/
http://www.cplusplus.com/doc/tutorial/basic_io/


1
2
3
4
while ( std::cin >> p.x >> p.y )
{
 // append to vector
}
Entering two coordinates (x,y) is the next code?

1
2
3
4
5
6
7
8
struct points {
    float x, y;
};

// ...

points p;
std::cin >> p.x >> p.y;


or?

1
2
3
4
5
6
7
8
9
10
struct points {
    float x;
    float y;
};

// ...

points p;
std::cin >> p.x;
std::cin >> p.y;
Yes - either work. Also, see @keskiverto's response for one example of how you might add values to a vector.
Thank you so much! Very helpful! :D
Topic archived. No new replies allowed.