Code:
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
Observation:
I now understand that std::emplace behaves like this:
The insertion only takes place if no other element in the container has a key equivalent to the one being emplaced (keys in a map container are unique).
Therefore my code is flawed. What I was hoping to acheive (in pseudo code) is:
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
By the end of this loop iteration I want to have the most recent sHitItem, for each person. But as it is, it is only adding an entry into the map if the name does not exist.
What is the simplest way to get around this?
Is the name in the map?...thing is just equivalent ofmapHistory[sHistItem.strName] = sHistItem;. operator[] does what you want if your data object is assignable.[]operator behaved like in a normal array where it would break if it was not valid. Thanks for the clarification.at()method for that. The [] behavior might be unwanted in some cases because it always creates an element if it doesn't exist. Though instead ofatit's better just to usefind. Once upon a time there was some controversial articles about this in regard to STL (then-Morozov's library) design.