Reputation: 8994
I'm a smidge rusty on using map and need a lil' help; I've declared the below.
std::map<std::string, std::vector<double>> myMap;
I'm periodically reading JSON data, where the ordering of data may sometimes change, or new data elements appear. Other parts of my code will loop through the JSON and extract two variables (jsonLabel, a string), and the associated value as a double (latestDouble).
If jsonLabel already exists, I want to add the associated latestDouble to the end of the vector; if it doesn't exist, make the new Key and start a vector.
I've tried the below; however I keep crashing. I'm presuming it's because map actually isn't smart enough to insert latestDouble at the end of the vector in the map.
myMap.insert(std::make_pair(jsonLabel, latestDouble));
Pseudo Example:
JSON parse #1: [A,43],[B,10],[C,9]
JSON parse #2: [A,10],[C,4],[B,3] /// Change in ordering
JSON parse #2: [A,8],[B,7],[C,2],[D,1] /// New element
Should result in:
A: 43,10,8
B: 10,3,7
C: 9,4,2
D: 1
Thanks for any help!
Upvotes: 0
Views: 861
Reputation: 409166
If the string in jsonLabel
already exists as a key in the map, then insert
will not insert anything into the map.
And the map insert
function is to insert into the map itself. The pair should be a pair of the key and value types (where the value should be a vector of doubles).
What you seem to want is simply
myMap[jsonLabel].push_back(latestDouble);
The operator[]
function will create a default-constructed value if the key doesn't exist, and as such will create an empty vector for you.
Upvotes: 7