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 point struct is used as a variable type in the line struct member definition. This is possible as long as the point struct is defined before the line struct

  • The getPoint function uses the point struct as a return type

  • The lineLength function needs to access a point 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 the cmath library to see more functions from the cmath library, you can Google β€˜c++ cmath’, or follow this link.

Last updated