我正在寻找一种方法来初始化std :: map中的第一个值,然后根据键初始化第二个值。这是我的代码:
#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"} };
};
我想要做的是,已经在课堂上使用这些键,然后使用构造函数初始化值,但当然在初始化地图时会出现错误,有什么帮助吗?
答案 0 :(得分:5)
使用构造函数
初始化值
您可以直接在构造函数中执行这两项操作:
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;
}
这仍然可以确保您的地图在整个课程有效期内有效并初始化。
答案 1 :(得分:0)
您可以编写一个(静态)函数来执行此操作:
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;
}
然后在你班上:
std::map<std::string, double> Subject_Scores = createMap( { "Maths", "English", "Chemistry", "Biology", "History" } );