2014-03-14 69 views
0

我試圖做到以下幾點:你如何創建地圖的地圖?

.h 
map<int, map<int,int> > forwardingTable; 

.cpp 
int 
UpdateForwardingTable(int dest, int hop, int cost) 
{ 
    if(forwardingTable.at(dest) != forwardingTable.end()) 
     forwardingTable.at(dest) = make_pair(hop, cost); 
    else 
     forwardingTable.insert(dest, make_pair(hop, cost)); 
} 

,但我得到一百萬編譯器錯誤,類似於:

In file included from /usr/include/c++/4.8/map:60:0, 
       from globals.h:25, 
       from rtngnode.h:2, 
       from rtngnode.cpp:1: 
/usr/include/c++/4.8/bits/stl_tree.h:316:5: note: template<class _Val> bool std::operator!=(const std::_Rb_tree_iterator<_Tp>&, const std::_Rb_tree_const_iterator<_Val>&) 
    operator!=(const _Rb_tree_iterator<_Val>& __x, 
    ^
/usr/include/c++/4.8/bits/stl_tree.h:316:5: note: template argument deduction/substitution failed: 
rtngnode.cpp:205:53: note: ‘std::map<int, std::map<int, int, std::less<int> > >::mapped_type {aka std::map<int, int, std::less<int> >}’ is not derived from ‘const std::_Rb_tree_iterator<_Tp>’ 
    if(forwardingTable.at(dest) != forwardingTable.end()) 

難道我做錯了什麼?這種類型的東西有更好的容器嗎?

+0

'.at'不返回一個迭代器,它返回一個'mapped_type&',即'的std ::地圖&'。 –

+2

我認爲你的意思是'find'而不是你第一次使用'at'。然而,之後的路線是沒有意義的。你可以用'forwardingTable [dest] [hop] = cost;' –

+0

@MattMcNabb sheesh替換這個完整的函數,這絕對容易得多。我感到很傻。 TY! – MrDuk

回答

1

有拖的問題:

1,make_pair回報pair,不map

2,at(dest)可能會拋出一個out_of_range異常,請參閱map::at

它應該是:

int 
UpdateForwardingTable(int dest, int hop, int cost) 
{ 
    map<int, map<int,int> >::iterator itr = forwardingTable.find(dest); 
    if(itr != forwardingTable.end()) 
    { 
     itr->second.insert(hop, cost); 
     // forwardingTable.at(dest) = make_pair(hop, cost); 
    } 
    else 
    { 
     map<int, int> obj; 
     obj.insert(hop, const); 
     forwardingTable.insert(dest, obj); 
     // forwardingTable.insert(dest, make_pair(hop, cost)); 
    } 
}