How do I pass a map as a parameter and add to it in this method?
Solution 1
Use &
to pass by reference:
void SetMapPairs(std::map<std::string, std::string>& mapPairs)
{
// ...
}
Solution 2
typedef std::map<std::string, std::string> MyMap;
void myMethod(MyMap &map)
{
map["fruit"] = "apple";
}
or
void myMethod(const MyMap &map)
{
//can't edit map here
}
Solution 3
You use &
to pass by reference:
void SetMapPairs(map<string, string> & mapPairs)
{ // ^ that means it's a reference
mapPairs["one"] = "two";
}
Solution 4
At least for this particular case, I think I'd probably return a map instead of passing one in by reference:
map<string, string> SetMapPairs() {
std::map<string, string> temp;
temp["one"] = "two";
return temp;
}
Then in your calling code, you can use something like:
map<string, string> MyMap = SetMapPairs();
With most decent/modern compilers the generated code will end up about the same either way, but I think under the circumstances, this is a better fit for what you're really doing.
Geekoder
I am a doctor in software engineering, working as a senior software developer for Allegorithmic.
Updated on June 19, 2020Comments
-
Geekoder almost 4 years
So I have a map
map<string, string> myMap; SetMapPairs(map); void SetMapPairs(map<string, string> mapPairs) { map<string, string> myMap = mapPairs; myMap["one"] = "two"; }
I know that I'm doing it wrong but I'm not sure how to do it.
How can I pass it by reference so that I can add to the map in this method?
Also I need to first setmyMap = mapPairs
otherwise I know it's easy to do
void SetMapPairs(map<string, string> &mapPairs)
-
juanchopanza almost 12 yearsAre you really calling
SetMapPairs(map);
? That shouldn't even compile.
-
-
Pittfall almost 12 yearsI tried that first and my map ends up empty after I finish with the method call
-
Pittfall almost 12 yearsI need to first set myMap to the mapPairs parameter because this will eventually be a parameter in a constructor
-
Pittfall almost 12 yearssorry, I thought the detail I provided was enough, I should've just said the whole thing. The reason I need to set it is because that SetMapPairs() method will actually be a constructor that takes a map and that's why I can't have it as a return type method
-
Jerry Coffin almost 12 years@Pittfall: That doesn't make much sense. A ctor should construct the object to which it belongs, not something you send to it as a parameter.
-
Pittfall almost 12 yearsyeah, maybe I need to re-think my design