How to check whether an iterator is uninitialized in C++? or compare an iterator against NULL?

87 Views Asked by At

I was implementing LRU Cache in C++.

Here is what the class looks like,

class LRUCache {
    private:
        int capacity;
        list<pair<int,int>> memory; // key,value
        unordered_map<int, list<pair<int,int>>::iterator> cache; // key, memAddr
    public:
        LRUCache(int capacity);
        ~LRUCache();
        void insert(int key, int val);
        int query(int key);
        void print();
};

For the query method,

int LRUCache::query(int key) {
    list<pair<int,int>>::iterator it = cache.at(key);

    // check if 'it' is NULL? or uninitialized and return some arbitrary value to indicate that the key is not found

    memory.erase(it);
    memory.push_front(*it);

    return it->second;
}

Have gone through this answer: Can I check a C++ iterator against null? Does not provide a solution for my use case. It is not possible to compare 'it' against list.end(), since there is no list corresponding to a key NOT FOUND.

How do we check whether it is uninitialized?

-- EDIT 1 --

A work around for the specific problem could be by using a conditional statement with cache.find(key) against cache.end().

However, why is it not possible to compare against an uninitialized iterator? What is the design philosophy behind it?

0

There are 0 best solutions below