How do I pass a map as a parameter and add to it in this method?

22,641

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.

Share:
22,641
Geekoder
Author by

Geekoder

I am a doctor in software engineering, working as a senior software developer for Allegorithmic.

Updated on June 19, 2020

Comments

  • Geekoder
    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 set myMap = mapPairs otherwise I know it's easy to do
    void SetMapPairs(map<string, string> &mapPairs)

    • juanchopanza
      juanchopanza almost 12 years
      Are you really calling SetMapPairs(map);? That shouldn't even compile.
  • Pittfall
    Pittfall almost 12 years
    I tried that first and my map ends up empty after I finish with the method call
  • Pittfall
    Pittfall almost 12 years
    I need to first set myMap to the mapPairs parameter because this will eventually be a parameter in a constructor
  • Pittfall
    Pittfall almost 12 years
    sorry, 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
    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
    Pittfall almost 12 years
    yeah, maybe I need to re-think my design