简体   繁体   中英

Accessing elements of a vector in a map of vectors

I want to create a map of vectors. 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?). This will be a map of vectors(of ints) where the keys are strings. My question is how to access a particular element in the vector to change is value in C++. Something along the lines of map_name['word'].[3]= 2 if i wanted to set the third value of the vector of "word" to 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.

The pattern is recursive.

That is, when you do:

expression[key] = value;

your expression doesn't have to just be a variable name; it can be a more complex expression, such as 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. 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 '.' you added was unnecessary because you're accessing an element inside another element, just like a 2D array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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