创建一个包含两种不同数据类型或类的向量 [英] Creating a vector that holds two different data types or classes
本文介绍了创建一个包含两种不同数据类型或类的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个包含int和字符串的向量。这是否可能?
I am trying to create a vector that holds an int and a string. Is this possible?
例如,我想要向量< int> myArr
来保存 string x =Picture This
For example I want vector<int>myArr
to hold string x= "Picture This"
推荐答案
您可以使用联合,但是有更好的替代方案。
You can use a union, but there are better alternatives.
您可以使用 boost :: variant
以获得此类功能:
You can use boost::variant
to get this kind of functionality:
using string_int = boost::variant<std::string, int>;
std::vector<string_int> vec;
要从变体中获取字符串或int,可以使用 boost :: get
:
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]);
这篇关于创建一个包含两种不同数据类型或类的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文