[英]A string vector inside an int vector?
I'm aware of multidimensional vectors for example vector<vector<int>>
but I was wondering if you can have a vector of a type inside a vector of another type. 我知道多维向量,例如
vector<vector<int>>
但是我想知道是否可以在另一种类型的向量中包含某种类型的向量。
An example would be a string vector inside an integer vector, so I would access it like this: 一个示例是整数向量内的字符串向量,因此我将这样访问它:
vectorName[0]["A"];
Can this be done? 能做到吗?
Thanks. 谢谢。
This expression is more appropriate for declaration 此表达式更适合于声明
std::vector<std::map<std::string, T>> vectorName;
In this case you will be able to write for example 在这种情况下,您将能够编写例如
T value = vectorName[0]["A"];
where T is some type. 其中T是某种类型。
std::vector
is a random access data structure by design, and is supposed to store a contiguous data array where the elements are accessible via an integral index number . std::vector
在设计上是一种随机访问数据结构,应该存储一个连续的数据数组,其中可以通过一个整数索引号访问这些元素。
You can not use std::vector
in the way you describe, it seems more like a string->value_type mapping, eg std::map<std::string, T>
. 您不能以描述的方式使用
std::vector
,它看起来更像是一个string-> value_type映射,例如std::map<std::string, T>
。
You could use a std::vector
of std::map
s to get the behaviour you want. 您可以使用
std::map
的std::vector
获得所需的行为。
std::vector<std::map<std::string, int>> vec{
{{"a1", 1}, {"a2", 2}},
{{"b1", 1}, {"b2", 2}}
};
std::cout << vec[0]["a2"] << std::endl; // 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.