Creating a vector that holds two different data types or classes

c++, polymorphism, vector

Solution

You can use a union, but there are better alternatives.

You can use `boost::variant` to get this kind of functionality:

using string_int = boost::variant<std::string, int>;

std::vector<string_int> vec;

To get either a string or an int out of a variant, you can use `boost::get`:

std::string& my_string = boost::get<std::string>(vec[0]);

Edit Well, it's 2017 now. You no longer need Boost to have `variant`, as we now have `std::variant`!

Problem

I am trying to create a vector that holds an int and a string. Is this possible? For example I want `vector<int>myArr` to hold `string x= "Picture This"`

Original source