Extract non-const pointer from iterator in a const member function

Viewed 27

I was doing some programs on Object Oreinted Programming in C++.

Here is a brief skeleton of the situation

class coll;
class ele {
    private:
        int val;
        coll* p;

    public:
        ele(int v, coll* p);
        int value() const;
        friend bool operator==(const ele& El1, const ele& El2);
        friend bool operator<(const ele& El1, const ele& El2);
};
class coll {
    private:
        set<ele> data;
    public:
        ele* min() const {
            if(size()) {
                set<ele>::iterator minIt = min_element(data.begin(), data.end());
                ele* ptr = &(*minIt);
                return ptr;
            }
            return nullptr;
        }
};

In the min() function, the return type has to be non-const and the function has to be const compulsorily.

I don't know why, but min_element's iterator when de-referenced is giving a const reference. Like, &(*minIt) is a const pointer. But I need a non-const pointer to return.

What can be the reason for this behavior. Thanks in advance.

0 Answers
Related