Initializing an array within a map container

Is there a method to initialize an array within a map container like this:

1
2
3
4
5
6
7
//...
map <string, double[3]> Grade;
//   Grade["Bobby Jay"] = {67.8, 44.5, 20.8}; //Faulty Instruction
   Grade["Bobby Jay"][0] = 67.8;  //Possible to avoid writing out each one?
   Grade["Bobby Jay"][1] = 44.5;
   Grade["Bobby Jay"][2] = 20.8;
//... 


in just one line?

Or is it better to use a structure object like this:

1
2
3
4
5
6
7
8
9
//...
struct Hold{
   double tile[3];
   //...
}
Hold Percent = {67.8, 44.5, 20.8};
map <string, Hold> Grade;
   Grade["Bobby Jay"] = Percent;
//... 
Last edited on
Wrong array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <map>
#include <array>
#include <string>

using namespace std;
int main()
{
    map <string, array<double,3>> Grade = {
                {"Bobby Jay",    {{67.8,  44.5, 20.8}} },
                {"Bobby Tables", {{999.0, -1.2, 3.14}} }
           };

    for(auto& p: Grade) {
        std::cout << "'" << p.first << "' => {";
        bool first=true;
        for(double d: p.second) {
            std::cout << (first?"":",") << d;
            first = false;
        }
    }
}


demo: http://ideone.com/ljgZCf (or, without the unnecessary braces, http://liveworkspace.org/code/248Rhh )

Thanks Cubbi.

I tried out your solution, and apparently, my outdated compiler doesn't have the necessary = operator function.

I'm going to update my compiler and try again. If it doesn't work, I'll find some way to emulate the array within a map.
You could initialize from an array on pretty much any compiler I can think of (with boost::array if std::array is not available), but that would be two lines, not one:

1
2
3
4
5
6
    pair<string, array<double,3> > Grade_init[] = {
                {"Bobby Jay",    {{67.8,  44.5, 20.8}} },
                {"Bobby Tables", {{999.0, -1.2, 3.14}} }
           };
    map <string, array<double,3>> Grade(Grade_init, Grade_init + 2);
Thanks for the suggestion. Luckily, after updating my compiler,

1
2
3
4
5
6
7
8
9
10
11
//...
         struct Hold{
         map<string, array<double, 3>> Grade;
         Hold(){
                   Grade["Bobby Jay"] = {{45.76, 100.0, 87.6}};
         }
         ~Hold(){
                   cout << Grade["Bobby Jay"][1];
         }
         };
//... 


was able to compile and outputted the correct float number.

Again, thanks for the help, Cubbi!
Topic archived. No new replies allowed.