Search code examples
c++arraysstdvectorstdmapstdarray

How to populate and edit a std::array of maps


I have an array of maps:

std::array<std::map<double, double>, 8> freqMap;

When populating this I need to add entries to the map at different array indices. I know I can create 8 different maps, populate them, and then add them to the array, but is it possible to keep appending entries to the maps directly in the array?

For example, how would I go about adding a map entries of key 5.0, val 3.3 to array index 2, and then add another entry to array index 3, and then append another entry to index 2 again and so on.

I can also use std::vector of maps, but still don't see a way to add entries this way.

Here is an example. I'm reading the data from a file and want to update my data structure directly:

while (fin >> arrayIdx >> key>> val)
    freqMaps[arrayIdx] = ??

Solution

  • You can simply do:

    while (fin >> arrayIdx >> key>> val)
      freqMaps[arrayIdx][key] = val;
    

    For example, how would I go about adding a map entries of key 5.0, val 3.3 to array index 2

    freqMaps[2][5.0] = 3.3;
    

    Here's a demo.

    Also, note that using double as keys in a std::map is not a good idea.