Nick
Nick

Reputation: 106

C++ initialize keys only in std::map

I'm looking for a way to initialize only first values in std::map and then initialize the second ones according to the keys. here is my code:

#pragma once
#include <string>
#include <map>

class Student
{
public:

    Student(
        double Score_Maths,
        double Score_Eng,
        double Score_Chem,
        double Score_Bio,
        double Score_His
        );
    ~Student();


private:

    std::string Surname;
    std::map<std::string, double> Subject_Scores = { {"Maths"}, {"English"}, {"Chemistry"}, {"Biology"}, {"History"} };

};

What I'm trying to do is, to have those keys in class already and then initialize the values using constructor, but of course it shows error when initializing map like that, any help?

Upvotes: 0

Views: 3949

Answers (2)

Slava
Slava

Reputation: 44258

You can write a (static) function to do that:

 std::map<std::string, double> Student::createMap( const std::vector<std::string> &v )
 {
     std::map<std::string, double> r;
     for( const auto &key : v ) r[ key ];
     return r;
 }

then in your class:

     std::map<std::string, double> Subject_Scores = createMap( { "Maths", "English", "Chemistry", "Biology", "History" } );

Upvotes: 0

Max Langhof
Max Langhof

Reputation: 23691

initialize the values using constructor

You can do both in the constructor directly:

https://godbolt.org/g/hWhcxu

class Student
{
public:

    Student(
        double Score_Maths,
        double Score_Eng,
        double Score_Chem,
        double Score_Bio,
        double Score_His
        )
        :
        Subject_Scores({ {"Maths", Score_Maths},
                         {"English", Score_Eng},
                         {"Chemistry", Score_Chem},
                         {"Biology", Score_Bio},
                         {"History", Score_His} })
    {
    }
    ~Student();

private:
    std::map<std::string, double> Subject_Scores;
}

This still ensures that your map is valid and initialized for the entire class lifetime.

Upvotes: 5

Related Questions