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>myArrto 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::variantto 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 vectorof uniontypes. 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::stringbut you need place the unionin a structwith 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::tupleif 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 vectormust only hold variables of the type declared within the angle brackets <>.
不, avector必须只包含尖括号中声明的类型的变量<>。
You could create a class that has an intmember and a stringmember, and then create a vectorto hold instances of that class, and then reference the intor stringmembers when you need to.
您可以创建一个具有int成员和string成员的类,然后创建一个vector来保存该类的实例,然后在需要时引用int或string成员。
回答by Mahesh
No. myArris instantiated to hold inttype. It can store only inttype.
编号myArr被实例化为持有int类型。它只能存储int类型。

