我需要更改std :: map中给定值的密钥。所以我写了这种方法:更改std :: map中的值的密钥
bool alter_key(_Kty oldKey, _Kty newKey)
{
std::map<_Kty, _Ty>::iterator it = this->find(newKey);
if(it != end()) //can't replace because newKey is already been used.
return false;
it = this->find(oldKey);
if(it == end()) // empty index.
return false;
_Ty value = it->second;
this->erase(it);
this->insert(std::pair<_Kty, _Ty>(newKey, value));
return true;
}
它的工作原理应该是这样,但是有可能优化此代码吗?
你已经分析了你的应用程序,发现这是一个瓶颈? – Borgleader
如果mapped_type复制的开销很大,请将其设置为唯一的/ shared_ptr。 –
是的,它对速度至关重要,但不幸的是我不是一个熟练的C++开发人员。 – Netherwire