find - C++ Best way to add new object in unordered_map -
i have unordered map std::unordered_map<unsigned int, myobject*> mydictionary.
when want add together entry, first want check if key exists. if does, need access object phone call function.
if key doesn't exists, want create new myobject key.
is improve create ?
myobject *my_obj; seek { my_obj = mydictionary.at(key); } grab (int e) { my_obj = new myobject(); mydictionary[key] = my_obj; } my_obj->function(); or ?
myobject *my_obj; if(mydictionary.find(key) == mydictionary->end()) { my_obj = new myobject(); mydictionary[key] = my_obj; } else { my_obj = mydictionary[key]; } my_obj->function(); or else ?
the best way map contain myobject instead of myobject *
std::unordered_map<unsigned int, myobject> mydictionary; and utilize
mydictionary[key].function(); // if key doesn't exist, it'll inserted assuming must utilize myobject *, utilize unique_ptr hold them instead of using raw pointers.
std::unordered_map<unsigned int, std::unique_ptr<myobject>> mydictionary; unsigned key = 42; if(mydictionary.find(key) == mydictionary.end()) { mydictionary.insert(std::make_pair(key, std::unique_ptr<myobject>(new myobject()))); } mydictionary[key]->function(); c++ find unordered-map
No comments:
Post a Comment