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];
}
Thanks for your reply. "void" is my typo. I think I was dumb when I
stated my question in above way. I got the answers from the replies
here now. Thanks to all.
btw : an off-topic question: I use thunderbird to read newsgroups.
recent ones shown was posted at yesterday). Is there anyone else
threads here. (I just came back from Mars and this is my first time