2.3.3 Using Structs: Line Length
Structs can be used like any other variable, so it is possible to do many things with them and use them in other data structures.
Using Structs with Vectors
A good example of extending structs is to use them in a vector. Since a struct is like any other variable, you can create a vector by using the struct name as a type. For example, given the point struct:
struct point {
int x, y;
};You can create and access elements like this:
vector<point> points;
point p1;
p1.x = 5;
p1.y = 10;
points.push_back(p1);
// Print x, y
cout << points[0].x << ", " << endl;Notice that you still use the [ ] operator then the . to acess the vector element and member respectively.
Other Examples
In thi example, you will see other extensions of structs. As you look through this example, take note of the following:
The
pointstruct is used as a variable type in thelinestruct member definition. This is possible as long as the point struct is defined before the line structThe
getPointfunction uses thepointstruct as a return typeThe
lineLengthfunction needs to access apointcoordinate from a given line. It does this by stacking the dot variables, i.e.line.point.xThis example uses the
powfunction from thecmathlibrary to see more functions from thecmathlibrary, you can Google ‘c++ cmath’, or follow this link.
Last updated