C++ 创建一个包含两种不同数据类型或类的向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17734042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a vector that holds two different data types or classes
提问by Person
I am trying to create a vector that holds an int and a string. Is this possible?
我正在尝试创建一个包含 int 和字符串的向量。这可能吗?
For example I want vector<int>myArr
to hold string x= "Picture This"
例如我想vector<int>myArr
持有string x= "Picture This"
回答by Mohamad Ali Baydoun
You can use a union, but there are better alternatives.
您可以使用联合,但还有更好的选择。
You can use boost::variant
to get this kind of functionality:
您可以使用boost::variant
来获得这种功能:
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
:
要从变体中获取字符串或整数,您可以使用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
!
编辑
好吧,现在是 2017 年。您不再需要 Boost 才能拥有variant
,就像我们现在拥有的一样std::variant
!
回答by devil
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 herealong with how you can tag the type. A small example:
是的,它可以容纳两个不同的类型,你可以创建vector
的union
类型。使用的空间将是较大的类型。这里解释了联合类型以及如何标记类型。一个小例子:
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.
您也可以使用,std::string
但您需要将union
放在struct
带有类型标记的a 中,以便析构函数选择要销毁的正确类型。请参阅链接的末尾。
回答by Casey
If you want the vector to hold two different types you can use a std::pair
(or std::tuple
if more than two)
如果您希望向量包含两种不同的类型,您可以使用 a std::pair
(或者std::tuple
如果超过两个)
In C++03:
在 C++03 中:
std::vector<std::pair<int, std::string> > myArr;
If you want the vector to hold one type that can be used as two different types: No, it can't be done.
如果您希望向量包含一种可以用作两种不同类型的类型:不,这是不可能的。
回答by Cory Klein
No, a vector
must only hold variables of the type declared within the angle brackets <
>
.
不, avector
必须只包含尖括号中声明的类型的变量<
>
。
You could create a class that has an int
member and a string
member, and then create a vector
to hold instances of that class, and then reference the int
or string
members when you need to.
您可以创建一个具有int
成员和string
成员的类,然后创建一个vector
来保存该类的实例,然后在需要时引用int
或string
成员。
回答by Mahesh
No. myArr
is instantiated to hold int
type. It can store only int
type.
编号myArr
被实例化为持有int
类型。它只能存储int
类型。