我有一个boost :: unordered_map,我想修改一个特定键的值。我在这里看到了这个问题。
使我的问题与众不同的是,在我的地图关键字中,键是一个简单的int,而我的值是std :: vector。我想通过在向量的第二个位置插入新的PoitCoord来更新此值。
一种解决方案是这样的:
auto it = map.find(key);
if(it != map.end())
{
std::vector<PointCoord> pntcrds = it->second;
pntcrds.insert((pntcrds.begin()+1), new_value);
it->second = pntcrds;
}
我想知道是否有较详细的解决方案。
如果我正确理解您的问题,则该地图与您的插入没有任何关系。您只修改了恰好存储在地图中的向量。您不是在修改地图的键,而是其中的一个值。
因此,简短的解决方案是:
auto it = map.find(key);
if(it != map.end() && !it->second.empty() )
{
it->second.insert( (pntcrds.begin()+1), new_value);
}
如果您知道该密钥存在于地图中,则可以将其缩短为:
std::vector<PointCords> & pntCords = map[key];
if( ! pntCords.empty() )
pntCords.insert( pntCords.begin()+1, new_value );
注意:如果您使用第二种方法,并且该键尚不存在,则默认构造的(= empty)std::vector<PointCords>
将插入到映射中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句