[英]How to access an index in a vector in a map from strings to vectors
If I have the following code, which stores 3 vectors as values in an unordered_map and maps to them via the string in their first index as a key:如果我有以下代码,它将 3 个向量作为值存储在 unordered_map 中,并通过它们的第一个索引中的字符串作为键映射到它们:
unordered_map<string, vector <vector<string>>> my_map;
vector<string> vec1 = {"banana", "apple"};
vector<string> vec2 = {"banana", "banana"};
vector<string> vec3 = {"banana", "pear"};
my_map["banana"].push_back(vec1);
my_map["banana"].push_back(vec2);
my_map["banana"].push_back(vec3);
cout << my_map["banana"][0] << my_map["banana"][1] << my_map["banana"][2];
How can I access specific indices of the unordered_map's vector?如何访问 unordered_map 向量的特定索引? I tried to do this in the last line but it does not work.
我试图在最后一行执行此操作,但它不起作用。 I have also tried using .at(0), etc instead of the double brackets but that also did not work.
我也尝试过使用 .at(0) 等代替双括号,但这也不起作用。
my_map["banana"][0]
is a std::vector<std::string>
, so you can't output that directly. my_map["banana"][0]
是std::vector<std::string>
,所以你不能直接输出。 You could overload the <<
operator, or just specify another index.您可以重载
<<
运算符,或者仅指定另一个索引。
std::unordered_map<std::string, std::vector<std::vector<std::string>>>
, where each key has a vector of vectors.
std::unordered_map<std::string, std::vector<std::vector<std::string>>>
,其中每个键都有一个向量向量。
So my_map["banana"].push_back(vec1)
pushes vec1
to the main vector.所以
my_map["banana"].push_back(vec1)
将vec1
推vec1
主向量。 If you want to access the values from vec1
, you have to specify 2 indices, because:如果要访问
vec1
的值,则必须指定 2 个索引,因为:
my_map["banana"][0] [0] ^^^^^^ ^ ^ key vector 0 element 0 in the vector (in main vector) at position 0 in the main vector
Note: This will return "banana"
注意:这将返回
"banana"
"pear"
, you would use:
"pear"
,你可以使用:
my_map["banana"] [2] [1] ^^^^^^^ ^ ^ key third vector second element (vec3) ("pear")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.