将项目“更新”到 map<key, shared_ptr<foo>> 的正确方法

Dmi*_*ruk 2 c++ stl map shared-ptr

我想将项目更新插入(更新或插入)到一个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]
}
Run Code Online (Sandbox Code Playgroud)

所以我想知道这是否是正确的做事方式。有find()效率吗?分配给positions[id]正确的方法来做到这一点,还是应该使用一些std::move构造?

Art*_*hur 5

最快的方法是尝试先插入并在未插入任何内容时更改迭代器值:

  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
  }
Run Code Online (Sandbox Code Playgroud)