更新标准::映射对象数据

Updating std::map object data

本文关键字:数据 对象 映射 更新 标准      更新时间:2023-10-16

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

通过引用传递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 = ...;
    }
}