代码之家  ›  专栏  ›  技术社区  ›  Dmitri Nesteruk

将项目“追加”到map中的正确方法<key,shared_ptr<foo>>

  •  2
  • Dmitri Nesteruk  · 技术社区  · 11 年前

    我想将项目追加(更新或插入)到 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 建筑

    3 回复  |  直到 11 年前
        1
  •  5
  •   0x26res    11 年前

    最快的方法是尝试先插入,如果未插入任何内容,则更改迭代器值:

      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
      }
    
        2
  •  0
  •   MatthiasB    11 年前

    然后(使用c++11),您可以在映射中放置元素,而不是使用运算符[]

    positions.emplace(id, make_shared<PortfolioEntry>(id,amount,price));
    

    如何处理更新取决于PortfolioEntry类。如果它只包含id、amount和price,并且构造成本很低,您可以简单地重写它,并完全放弃更新用例。如果它更复杂,那么无论如何都必须执行更新代码。

        3
  •  0
  •   vmax33    11 年前

    对于追加促销,您可以使用下一行:

    positions[id] = make_shared<PortfolioEntry>(id, amount, price);
    

    如果它已经存在-它将被替换为新值,如果不存在-它将会被插入。 你不需要打电话给find。 以上1行即可完成此任务。