代码之家  ›  专栏  ›  技术社区  ›  Andrew Truckle

使用std::emplace构建std::map并发布

  •  0
  • Andrew Truckle  · 技术社区  · 4 年前

    std::map<CString, S_DISCUSSION_HIST_ITEM> mapHistory;
    // History list is in ascending date order
    for (auto& sHistItem : m_listDiscussionItemHist)
    {
        if (m_bFullHistoryMode)
            mapHistory.emplace(sHistItem.strName, sHistItem);
        else if (sHistItem.eSchool == m_eActiveSchool)
            mapHistory.emplace(sHistItem.strName, sHistItem);
    }
    // The map is sorted by Name (so reset by date later)
    // The map has the latest assignment info for each Name now
    

    我现在明白了 std::emplace 行为如下:

    仅当容器中没有其他元素具有与正在放置的元素等效的键(贴图容器中的键是唯一的)时,才会进行插入。

    For Each History Item
       Is the name in the map?
          No, so add to map with sHitItem
          Yes, so replace the sHistItem with this one
    End Loop
    

    在这个循环迭代结束时,我希望得到最新的 sHitItem,

    1 回复  |  直到 4 年前
        1
  •  1
  •   Alex Guteniev    4 年前

    使用 insert_or_assign [] 运算符后跟赋值,如果它不存在,则将默认构造项。

    推荐文章