【问题标题】:Values aren't updated when using operator[][] on type: map<int, map<int, int> >在类型上使用 operator[][] 时值不会更新:map<int, map<int, int>>
【发布时间】:2014-03-23 06:39:15
【问题描述】:

我有一个程序,它充当一种虚拟路由器 ...我将我的转发表存储在地图的地图中:map&lt;int, map&lt;int,int&gt; &gt; --- 在我尝试调用之前,以下是我的转发表的当前状态,之前已初始化:

//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

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

【问题讨论】:

    标签: c++ map insert iterator


    【解决方案1】:

    注意3705

    forwardingTable[3701][3705] = 6
    

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 2015-11-30
      • 1970-01-01
      相关资源
      最近更新 更多