gpt4 book ai didi

c++ - 如何创建 map 中的 map ?

转载 作者:行者123 更新时间:2023-11-28 07:01:34 25 4
gpt4 key购买 nike

我正在尝试执行以下操作:

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

我做错了什么吗?这种东西有更好的容器吗?

最佳答案

有两个问题:

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

关于c++ - 如何创建 map 中的 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22396588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com