Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a vector that holds two different data types or classes

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"

like image 715
Person Avatar asked Jul 18 '13 21:07

Person


People also ask

Can a vector contain multiple data types?

Yes it is possible to hold two different types, you can create a vector of union types.

Can vector store different types of data?

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.

Can we store different data types in vector C++?

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.

Is a special type of vector which contains elements of different 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.


2 Answers

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!

like image 176
user123 Avatar answered Oct 12 '22 14:10

user123


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.

like image 21
devil Avatar answered Oct 12 '22 14:10

devil