Heterogenous Collections Using Variant
Explore how to build and manipulate heterogeneous collections with std::variant and std::vector. Learn to store multiple types dynamically, iterate with std::visit, and safely access elements using std::holds_alternative and std::get.
We'll cover the following...
We'll cover the following...
Variant use in heterogenous collections
Now that we have a variant that can store any provided list, we can expand this to a heterogeneous collection. We do this by simply creating a std::vector of our variant:
We can now push elements of different types to our vector:
The vector will now look like this in memory, where every element in the vector contains the size of the variant, which in this case is sizeof(std::size_t) + sizeof(std::string):
Of course, we can also pop_back() or modify the container in any other way the container allows: