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:
You can create and access elements like this:
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
point
struct is used as a variable type in theline
struct member definition. This is possible as long as the point struct is defined before the line structThe
getPoint
function uses thepoint
struct as a return typeThe
lineLength
function needs to access apoint
coordinate from a given line. It does this by stacking the dot variables, i.e.line.point.x
This example uses the
pow
function from thecmath
library to see more functions from thecmath
library, you can Google ‘c++ cmath’, or follow this link.
Last updated