0

我有一个 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 中的值。我怎样才能做到这一点?

4

1 回答 1

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 = ...;
    }
}
于 2012-04-23T23:31:30.787 回答