2

所以我有一张地图

map<string, string> myMap;

SetMapPairs(map);

void SetMapPairs(map<string, string> mapPairs)
{  
    map<string, string> myMap = mapPairs;
    myMap["one"] = "two";
}

我知道我做错了,但我不知道该怎么做。
如何通过引用传递它,以便我可以在此方法中添加到地图中?
另外我需要先设置,myMap = mapPairs否则我知道这很容易做到
void SetMapPairs(map<string, string> &mapPairs)

4

4 回答 4

12

用于&通过引用传递:

void SetMapPairs(std::map<std::string, std::string>& mapPairs)
{
    // ...
}
于 2012-06-18T13:24:44.660 回答
4
typedef std::map<std::string, std::string> MyMap;


void myMethod(MyMap &map)
{
    map["fruit"] = "apple";
}

或者

void myMethod(const MyMap &map)
{
    //can't edit map here
}
于 2012-06-18T13:23:59.350 回答
3

您使用&通过引用传递:

void SetMapPairs(map<string, string> & mapPairs)
{                                 // ^ that means it's a reference
    mapPairs["one"] = "two";
}
于 2012-06-18T13:25:36.593 回答
1

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.

于 2012-06-18T13:33:20.410 回答