![](/img/trans.png)
[英]Insert or update into an unordered_map without requiring a default constructor
[英]Is there a better way to do a find with optional insert using unordered_map of objects with no default constructor?
我有以下代碼:
class CEvent
{
public:
CEvent(std::string const&) {}
};
std::unordered_map<std::string, CEvent> m_messageList;
CEvent& GetMessageEvent(std::string const& name)
{
auto it = m_messageList.find(name);
if (it == m_messageList.end())
{
auto pair = m_messageList.emplace(std::piecewise_construct,
std::forward_as_tuple(name), // Copy-construct 'name' as the key
std::forward_as_tuple(name)); // Construct CEvent in-place with the name
return pair.first->second;
}
return it->second;
}
( 現場樣本 )
我認為代碼是非常干凈的,但我不喜歡,我必須做一個find
從單獨emplace
。 有沒有辦法更好地做到這一點? 或者這“足夠好”? 我知道我可能會調用emplace
而不是先find
,以完成這兩項任務,但這意味着每次創建一個CEvent
,即使沒有真正的插入。
一旦C ++ 17發布(或者如果您的編譯器支持預發布版本),
return m_messageList.try_emplace(name, name).first;
應該做的伎倆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.