c++ - 将 'upserting' 项放入 map<key, shared_ptr<foo>> 的正确方法

标签 c++ dictionary stl 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]
}

所以我想知道这是否是正确的做事方式。是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/

相关文章:

c++ - 定义结构并用作参数

c++ - exe和dll共享同一个静态库

python - 使用 biopython 从外部 pubmed ID 列表中提取多个摘要

c++ - 从 C++ 中的 vector 获取指针 vector

c++ - 具有调试功能的 C/C++ IDE 的建议

c++ - 给定从键到索引的映射,将值 (mapped_type) 从映射复制到 vector

c++ - 通过引用使用 vector<int>::iterator 但有错误

c++ - 通过更高级别的结构访问子变量

java - 是否存在具有不同值类型的多重映射

c - Stdin + 字典文本替换工具 -- 调试