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"
Yes it is possible to hold two different types, you can create a vector of union types.
The easiest way to store multiple types in the same vector is to make them subtypes of a parent class, wrapping your desired types in classes if they aren't classes already.
On the other hand, The standard container like vector and list that comes with C++ is already generic. The main problem with them is they can be the container for any data type but they must be of the same type. In other words, they cannot contain multiple data types.
A list is a special type of vector. Each element can be a different type. The content of elements of a list can be retrieved by using double square brackets.
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
!
Yes it is possible to hold two different types, you can create a vector
of union
types. The space used will be the larger of the types. Union types are explained here along with how you can tag the type. A small example:
union Numeric
{
int i;
float f;
};
std::vector<Numeric> someNumbers;
Numeric n;
n.i = 4;
someNumbers.push_back(n);
You can also use std::string
but you need place the union
in a struct
with a type tag for the destructor to choose the correct type to destroy. See the end of the link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With