I have an abstract class called Object and I am using std::unordered_map<int, Object*> objects to contain these Objects within a class called DataSet. Each object has an id associated with it.
Normally, when deleting an object from my unordered_map, I can just do iterator = find(id) and then call erase on that iterator.
This is easy and efficient. The problem is, I have to implement a method to delete an entry/pair by value, rather then by the key (which was my id). This gives me the following prototype:
int DataSet::DeleteObject(Object* object)
What is the most efficient way of accomplishing this though? I'm thinking I can do something like this:
if(object){
for(auto kv : objects) {
if(kv.second == object) {
objects.erase(kv);
}
}
return 1;
}
But it seems very inefficient. So what would be the most efficient way to accomplish this?
erase?erase(kv)doesn't work. You have to erase by key, not by value, i.e.erase(kv.first).