hi,
a simple one : how to create an unordered map of fixed size vectors?
thnxCode:unordered_map<string, vector<int>> x; x["mumb 5"][7] = 65; // this does not work since my vector size is not set.
hi,
a simple one : how to create an unordered map of fixed size vectors?
thnxCode:unordered_map<string, vector<int>> x; x["mumb 5"][7] = 65; // this does not work since my vector size is not set.
you have to create enough space for a value at index 7 in your vector. the easiest way to do this is by calling the resize() member function on an entry in your map.
What can this strange device be?
When I touch it, it gives forth a sound
It's got wires that vibrate and give music
What can this thing be that I found?
auto & vec = x["mumb 5"]; // Get vector
vec.resize(8); // Resize to make index 7 valid
vec.at(7) = 65; // Fill element
Best is to use push_back. Avoid index operator since it can cause undefined behaviour if you access out-of-bounds elements. .at() function helps you catch these programming errors earlier.
In C++11 the easiest way is to use an std::array:
Code:unordered_map<string, array<int,8>> x; x["mumb 5"][7] = 65;
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.
I suspect you're referring to the vector's index operator. both the map and its vector elements have an index operator in this case, so it was a little unclear to me at first which one you were referring to.
just to clarify for the OP, there's no risk of "out of bounds" access with the map itself. using an "index" that doesn't exist in an stl map will simply create that element and return its associated value.
but only if you know you need fixed size elements, whose size is known at compile time.
What can this strange device be?
When I touch it, it gives forth a sound
It's got wires that vibrate and give music
What can this thing be that I found?
What can this strange device be?
When I touch it, it gives forth a sound
It's got wires that vibrate and give music
What can this thing be that I found?