我想将项目更新插入(更新或插入)到 map<int,shared_ptr<PortfolioEntry>>
结构。我当前的代码如下所示:
auto existing = positions.find(id);
if (existing == positions.end())
{
positions[id] = make_shared<PortfolioEntry>(id, amount, price);
}
else
{
// update positions[id]
}
所以我想知道这是否是正确的做事方式。是find()
高效的?正在分配给 positions[id]
正确的方法来做到这一点,或者我应该使用一些 std::move
构造?
最佳答案
最快的方法是先尝试插入,如果没有插入,则更改迭代器值:
template < class KeyType, class ElementType >
bool SetAndCheckChanged(
std::map< KeyType, ElementType >& the_map,
KeyType const& key,
ElementType const& new_value)
{
typedef typename std::map< KeyType, ElementType >::iterator Iterator;
typedef typename std::pair< Iterator, bool > Result;
Result result = the_map.insert(typename std::map< KeyType, ElementType >::value_type(key, new_value));
if (!result.second)
{
if ( !(result.first->second == new_value ))
{
result.first->second = new_value;
return true;
}
else
return false; // it was the same
}
else
return true; // changed cause not existing
}
关于c++ - 将 'upserting' 项放入 map<key, shared_ptr<foo>> 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22192068/