首先看一下在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