开发者

How to pass 2D map as a pointer to function

I have 2 maps:

map<int, map<int, int> > m1;
map<int, map<int, int> > m2;

And want to fill them in with a function:

void fillMaps (m1, m2) {
    * m1[0][0] = 5;
    * m2[0][1] = 4;
}

How should i pass those maps to the function? I guess the variable itself can be passed just like this:

map<int, map<int, int> > m1;
map<int, map<int, int> > 开发者_C百科m2;

fillMaps(m1, m2);

But how should i define types of variables inside the function to be able to change values of the map?


To change the maps in the function you'll want to pass them by reference:

void fillMaps (map<int, map<int, int> >& m1, map<int, map<int, int> >& m2) {
    m1[0][0] = 5;
    m2[0][1] = 4;
}

Note that there are spaces between the close angle braces to prevent weird compiler errors. Also note that with the pass by reference, you don't need to use any pointer dereferences; this is handled automatically.


You can pass the maps by reference or pointer to modify the values.

void fillMapsByReference (
    std::map<int, map<int, int> >& m1,
    std::map<int, map<int, int> >& m2)     {
    m1[0][0] = 5;
    m2[0][1] = 4;
}

void fillMapsByPointer (
    std::map<int, map<int, int> >* m1,
    std::map<int, map<int, int> >* m2)     {
    *m1[0][0] = 5;
    *m2[0][1] = 4;
}


I'll provide a bit different answer from others. You can use C++ templates and make the compiler automatically infer the types for you:

template <typename T>
void fillMaps (T& m1, T& m2) {
    m1[0][0] = 5;
    m2[0][1] = 4;
}

Call it like this:

map<int, map<int, int> > m1;
map<int, map<int, int> > m2;

fillMaps(m1, m2);

This way you pass the maps by reference. Also, if you later change the type of the maps (for example using another map implementation or using strings instead of ints), you won't have to change this function.


Use typedef to make the code cleaner:

typedef map<int, map<int, int> > intmap;

void fillMaps(intmap &m1, intmap &m2)
{
     m1[0][0] = 5;
     m2[0][1] = 4;
}


Here is my approach:

template <typename T>
class MapOfMaps
{
  public:
    // ...

  private:
    map<T, map<T, T> > m;
};

typedef MapOfMaps<int> MapOfIntMap;

void fillmap(MapOfIntMap& m1, MapOfIntMap& m2)
{
//...
}


Pass the value by reference. Also, you need to declare the type of m1 and m2 in fillMaps.

void fillMaps(map<int, map<int,int> > &m1, map<int, map<int,int> > &m2)
{
     // fill map code in here
     m1[0][0] = 5;
     m2[0][1] = 4;
}

Then, to call use fillMaps(m1, m2);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜