Vector of Structs#
Let’s look at a program that stores the basic properties for the planets in our solar system and then loops over them and computes their orbital period using Kepler’s third law:
#include <iostream>
#include <vector>
#include <cmath>
#include <format>
#include <string>
struct Planet {
std::string name;
double a{}; // semi-major axis
double e{}; // eccentricity
};
int main() {
const std::vector<Planet> planets{{.name="Mercury", .a=0.3871, .e=0.2056},
{.name="Venus", .a=0.7233, .e=0.0068},
{.name="Earth", .a=1.0000, .e=0.0167},
{.name="Mars", .a=1.5237, .e=0.0934},
{.name="Jupiter", .a=5.2029, .e=0.0484},
{.name="Saturn", .a=9.5370, .e=0.0539},
{.name="Uranus", .a=19.189, .e=0.0473},
{.name="Neptune", .a=30.070, .e=0.0086}};
for (auto p : planets) {
std::cout << std::format("{} has a period of {:.2f} years\n",
p.name, std::sqrt(std::pow(p.a, 3.0)));
}
}
Some notes:
We will use a vector of our
struct:std::vector<Planet> planets;
This is no different than when we made vectors of
doubleor other types. We still index it the same and the same member functions can be used.We put the definition of
Planetoutside of themain()function.In the initialization of the
planetsvector, we use list-initialization for each of the planets in its own set of{}.Notice that our vector
planetsisconst. This means that we cannot add to it (e.g., via.push_back()).
Note
As mentioned above, a class is very similar to a struct in
C++. The main difference is that in a struct all of the
members are publicly accessible while in a class, they are
private unless we make them public.
Note
A common consideration when organizing data that is associated together is whether to do a struct-of-arrays or an array-of-structs. See this discussion on AoS and SoA.
In our planet example above, we created an array of structs. This is a natural organization if we want to loop over planets and access their data individually.