Re: assignment/initialization of container - map
xuatla wrote:
I want to define a map:
std::map<string, int> myMap;
e.g., the score of students. Then I can assign the value as follows:
myMap["stud1"] = 90;
myMap["stud2"] = 60;
...
My question now is: can I assign the name of many students in one line?
e.g., for array we have the following way:
int myArray[] = { 1, 3, 4, 5 };
Do we have similar way for map?
No.
std::map<string, int> myMap = { ("stud1", 90), ("stud2", 60) };
// wrong code
Another question: how can I print the score of a given student's name?
void getScore(std::map<string, int> myMap, const std::string& stuName)
{
return myMap.find(stuName)->second();
}
Is this correct? Any better solution?
First, unless you want to DRASTICALLY inefficient, better to pass the
map by reference instead of by value. Second, you can't return a value
if you declare the function void. Finally, although theoretically
slightly less efficient, more clear in my view is to use operator[] and
dump the separate function altogether:
myMap[stuName]
or if you insist on the separate function, make it:
int getScore(std::map<string, int>& myMap, const std::string& stuName)
{
return myMap[stuName];
}
Best regards,
Tom