更新std :: map对象数据

时间:2012-04-23 23:28:55

标签: c++

我有一个std :: map对象,如下所示

typedef std::map<int,int> RoutingTable;
RoutingTable rtable;

然后我在函数

中初始化它
 for (int i=0; i<getNumNodes(); i++)
 {
   int gateIndex = parentModuleGate->getIndex();
    int address = topo->getNode(i)->getModule()->par("address");
    rtable[address] = gateIndex; 
  }

现在我想在另一个函数中更改rtable中的值。我怎么能实现这个目标呢?

1 个答案:

答案 0 :(得分:2)

通过引用传递rtable

void some_func(std::map<int, int>& a_rtable)
{
    // Either iterate over each entry in the map and
    // perform some modification to its values.
    for (std::map<int, int>::iterator i = a_rtable.begin();
         i != a_rtable.end();
         i++)
    {
        i->second = ...;
    }

    // Or just directly access the necessary values for
    // modification.
    a_rtable[0] = ...; // Note this would add entry for '0' if one
                       // did not exist so you could use
                       // std::map::find() (or similar) to avoid new
                       // entry creation.

    std::map<int, int>::iterator i = a_rtable.find(5);
    if (i != a_rtable.end())
    {
        i->second = ...;
    }
}