1

Algorithms and member functions are suggested over looping for efficiency when working with containers. However, associative containers (unordered_map) does not work with the erase(remove_if) paradigm, it appears that the common method is to fall back on a loop.

uom is a std::unordered_map

for(auto it = uom.begin() ; it!=uom.end(); ){
    if(it->second->toErase()) {
        delete it->second; // omit delete if using std::unique_ptr
        fpc.erase(it++);
    }else{
        ++it;
    }
}

//as per Scott Meyers Effective STL pg45

is this as efficient as possible? It seams like there should be a better way to do this using something like the erase(remove_if) paradigm but that works for unordered_map (I understand that the associative containers cannot be "re-ordered" hence the non-support of the remove_if algorithm). Is this really the best way to erase entries from an unordered_map using a predicate? Any suggestions?

Thank you in advance.

Dave M
  • 11
  • 2

1 Answers1

0

That is as efficient as possible. If you want something more convenient, you could use boost's erase_if template - see here. unordered_map maintains a linked list of nodes in each bucket, so it's cheap to erase them. There's no need of remove-if type "compaction", which suits std::vector's use of contiguous memory.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252