Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

c++ - 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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...