Search⌘ K
AI Features

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.

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:

C++
using VariantType = std::variant<int, std::string, bool>;
auto container = std::vector<VariantType>{};

We can now push elements of different types to our vector:

C++
container.push_back(false);
container.push_back("I am a string");
container.push_back("I am also a string");
container.push_back(13);

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):

Vector of variants
Vector of variants

Of course, we can also pop_back() or modify the container in any other way the container allows:

C++
container.pop_back();
std::reverse(container.begin(), container.end());
// etc...

Accessing

...