c++ - Is there a better way to do a find with optional insert using unordered_map of objects with no default constructor? -
i have following code:
class cevent { public: cevent(std::string const&) {} }; std::unordered_map<std::string, cevent> m_messagelist; cevent& getmessageevent(std::string const& name) { auto = 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' key std::forward_as_tuple(name)); // construct cevent in-place name return pair.first->second; } return it->second; } i think code pretty clean, don't have find separate emplace. there way better? or "good enough"? know call emplace instead of find first, accomplish both tasks, means creating cevent every time, if no real insert happens.
once c++17 released (or if compiler supports prerelease versions),
return m_messagelist.try_emplace(name, name).first; should trick.
Comments
Post a Comment