如何更新map、multimap中得key

首先看一下在stl中的语法:

template <typename K, typename V, typename Compare = less<K>, typename Allocator = allocator<pair<const K, V> > > class map; template <typename K, typename V, typename Compare = less<K>, typename Allocator = allocator<pair<const K, V> > > class multimap;

map和multimap的定义差不多,除了multimap可以有多个相同的key值, map根据Compare来对key进行排序,Compaer可以是less,greater等stl自带的,你也可以自己定义Compare。

现在回到正题,如何改变key值,其实没有什么办法,只有选择插入删除操作:即插入新的pair对,删除旧的pair对。 详见下面的code:

namespace My_Utility{
template <typename CONTAINER>
    void replace_key(CONTAINER& container,
                     const typename CONTAINER::key_type& oldKey,
                     const typename CONTAINER::key_type& newKey)
    {
        if(!container.key_comp()(oldKey,newKey) && !container.key_comp()(newKey,oldKey)){
	    return;} //Thanks to Graham for this Fix
        typename CONTAINER::iterator begin(container.find(oldKey));
        for(;;){
            if(begin != container.end()){
                container.insert(typename CONTAINER::value_type(newKey, begin->second));
                container.erase(begin); // Thanks to Graham for this potential fix
                begin = container.find(oldKey);
            }
            else{
                return;
            }
        }
    }
}

原文链接: http://www.codeproject.com/Articles/36326/How-To-Update-Your-Const-Key-Fields-in-a-Map-Multi

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值