Domanda

I'm trying to do the following:

.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));
}

But I get a million compiler errors, similar to:

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())

Am I doing something wrong? Is there a better container for this type of thing?

È stato utile?

Soluzione

There are tow problems:

1, make_pair returns pair, not map.

2, at(dest) may throws an out_of_range exception, refer map::at

It should be:

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));
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top