【发布时间】:2013-08-23 01:02:01
【问题描述】:
我需要更改 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;
}
它应该可以正常工作,但是可以优化这段代码吗?
【问题讨论】:
-
您已经分析了您的应用程序并发现这是一个瓶颈?
-
如果 mapped_type 的复制成本很高,请将其设为 unique/shared_ptr。
-
是的,它对速度至关重要,但不幸的是我不是一个熟练的 c++ 开发人员。
-
那么哪一部分是您确定的瓶颈?,地图插入(您什么都不做会使其更快)或对象复制?
-
如果 _Ty 不是指针,则复制对象。
标签: c++ dictionary map stl key-value