在类型上使用运算符 [][] 时,不会更新值:map<int、map<int、int> >

Values aren't updated when using operator[][] on type: map<int, map<int, int> >

本文关键字:int map lt gt 更新 类型 运算符      更新时间:2023-10-16

我有一个程序,作为一种虚拟路由器…我将转发表存储在映射的映射中:map<int, map<int,int> >——在我尝试调用之前,下面是我的转发表的当前状态,已经初始化:

//destination | hop, cost
map<int, map<int,int> > forwardingTable;
forwardingTable[3701][3701] = 8;

现在我正在尝试做以下事情:

//iterators and pathCost are initialized earlier
forwardingTable[topoIt->first][*pIter] = pathCost;
cout << "forwardingTable[" << topoIt->first << "][" << *pIter << "] = " << pathCost << endl;
这样,我得到的输出是:
forwardingTable[3701][3705] = 6

然而,在同样的方法中,当我遍历转发表时:

forwardingTableIter iter = forwardingTable.begin(); 
while(iter != forwardingTable.end())
{
    map<int,int, less<int> >::iterator inner_it = iter->second.begin();
    cout << "--Dest: " << iter->first << "tHop: " << inner_it->first << "tCost: " << inner_it->second << endl;
    iter++;
}

当它到达节点3701时,我得到以下输出:

//still hop 3701, cost of 8
--Dest: 3701    Hop: 3701   Cost: 8

我误解了[][]运算符了吗?我的印象是,它会搜索引用的元素,如果找到,更新它-否则,插入它。

注意3705

forwardingTable[3701][3705] = 6
相关文章: