Search code examples
c++pointersiteratordestructor

How can I iterate through unordered_map which is in struct?


I have the following struct:

struct Node;

typedef unordered_map<char, Node*> Table;

struct Node {
    Table table = {{'\0', nullptr}};
    bool terminal = false;
};

which I use in the class to store the items. So I am trying to write the destructor. My idea was recursively iterate through all nodes until we reach a node with an empty table and then clear the memory for the structure, and then remove the element from the table. But the problem is that it can't compare begin and end iterators.

void clear_memory(Node * cur_node) {
    if (cur_node->table.empty()) {
        delete cur_node;
        return;
    }
    auto it = cur_node->table.begin();
    while (it < cur_node->table.end()) {
        clear_memory(it->second);
        it = cur_node->table.erase(it);
    }
}

~SomeClass() {
    clear_memory(head);
}

I was trying to use range-based for loop and it works fine, but I need exactly iterators to erase the elements from table.

P.S. I know that using pointers in that way is a bad idea, but it is study assignment.


Solution

  • You should check for unequality.

        while (it != cur_node->table.end()) {