Skip to content

Instantly share code, notes, and snippets.

@jcward
Created January 22, 2015 07:27
Show Gist options
  • Save jcward/2171e7b4b7f9d9dfc236 to your computer and use it in GitHub Desktop.
Save jcward/2171e7b4b7f9d9dfc236 to your computer and use it in GitHub Desktop.
Traversing (and populating where nodes don't exist) a hierarchical structure in a std::map
// Traversing (and populating where nodes don't exist) a hierarchical structure:
struct AllocStackIdMapEntry
{
std::map<int, AllocStackIdMapEntry*> children;
};
{
std::vector<int> callstack;
AllocStackIdMapEntry *ptr = &root;
int i=0;
while (i<size) {
int id = callstack.at(i++);
//printf("Finding child with id=%d, ptr now %#010x\n", id, ptr);
std::map<int, AllocStackIdMapEntry*>::iterator lb = ptr->children.lower_bound(id);
if (lb != ptr->children.end() && !(ptr->children.key_comp()(id, lb->first)))
{ // key already exists
ptr = lb->second;
} else {
// the key does not exist in the map, add it
AllocStackIdMapEntry *newEntry = new AllocStackIdMapEntry();
ptr->children.insert(lb, std::map<int, AllocStackIdMapEntry*>::value_type(id, newEntry));
ptr = newEntry;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment