简体   繁体   English

访问向量的 map 中的向量元素

[英]Accessing elements of a vector in a map of vectors

I want to create a map of vectors.我想创建一个向量的 map。 I want the vector to be a private member variable however so when I need to increase the size of the vector for a particular key in the map it does it for all other keys in the map also(would that work?).我希望向量成为私有成员变量,但是当我需要为 map 中的特定键增加向量的大小时,它也会对 map 中的所有其他键执行此操作(这行得通吗?)。 This will be a map of vectors(of ints) where the keys are strings.这将是向量(整数)的 map,其中键是字符串。 My question is how to access a particular element in the vector to change is value in C++.我的问题是如何访问向量中的特定元素以更改 C++ 中的值。 Something along the lines of map_name['word'].[3]类似于 map_name['word'].[3] 的内容= 2 if i wanted to set the third value of the vector of "word" to 2. = 2 如果我想将“单词”向量的第三个值设置为 2。

enter image description here在此处输入图像描述

enter image description here Im still having trouble figuring out how to make it so the size of each vector for all the keys in the maps is modifiable so i can increase the size of each vector at any point along the program.在此处输入图像描述我仍然无法弄清楚如何制作它,因此地图中所有键的每个向量的大小都是可修改的,因此我可以在程序中的任何点增加每个向量的大小。 This is b/c the vector size is unknown at runtime and iterating through each element in the map to change the vector size will take too long.这是 b/c 向量大小在运行时是未知的,并且迭代 map 中的每个元素以更改向量大小将花费太长时间。

The pattern is recursive.该模式是递归的。

That is, when you do:也就是说,当你这样做时:

expression[key] = value;

your expression doesn't have to just be a variable name;您的expression不必只是一个变量名; it can be a more complex expression, such as map_name["word"] .它可以是更复杂的表达式,例如map_name["word"]

So:所以:

map_name["word"][3] = 2;

Regarding the first question, yes it is possible as mentioned in one of the comments, you can make your imaginary class to do that.关于第一个问题,是的,正如其中一个评论中提到的那样,您可以让您想象中的 class 做到这一点。 And in the second question, you'll have to access an element of a vector which is an element of a map like this: map1["abc"][1] = 2 The '.'在第二个问题中,您必须访问向量的元素,该元素是 map 的元素,如下所示: map1["abc"][1] = 2 The '.' you added was unnecessary because you're accessing an element inside another element, just like a 2D array您添加是不必要的,因为您正在访问另一个元素内的元素,就像二维数组一样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM