Re: assignment/initialization of container - map
Thomas Tutone <Thomas8675309@yahoo.com> wrote:
xuatla wrote:
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];
}
However, if stuName is not already in the map, the myMap[stuName]
version will automatically create an entry for it, and
default-initialize(?, maybe it's zero-initialize) it. Using
myMap.find(), this case can be handled separately if desired.
// untested and uncompiled
int getScore(const std::map<std::string, int>& myMap,
const std::string& stuName)
{
std::map<std::string, int>::const_iterator i = myMap.find(stuName);
if (i != myMap.end()) {
return i->second;
}
else {
return -1;
}
}
I do agree that the myMap[stuName] syntax is easier to read though,
however it cannot be used on a const map (or a reference to a const map)
because of the automatic-entry-creation behavior.
--
Marcus Kwok
Replace 'invalid' with 'net' to reply