James Wilks
James Wilks

Reputation: 740

const function and references

If you notice in the following functions they both have the same for loop that searches for a integer location. Pop() compiles but I get an error for top() having to do with the const qualifiers. The heap class inherits from eecs281heap which stores a functor Comp compare where Comp is the typename. The instructor told us the only way to access the functor is through this->() so i'm just lookin for some guidance here. Thanks

error: passing ‘const larger’ as ‘this’ argument of ‘bool larger::operator()(int, int)’ discards qualifiers

This happens after running the following in int main. Through testing I already know the constructor works properly.

vector <int> data={10,2,13};
poorman_heap<int,larger> y(data.begin(),data.end());

template<typename TYPE, typename COMP>
void poorman_heap<TYPE, COMP>::pop() {
    int location=0;
    for(int i=1;i<data.size();i++){
        if(this->compare(data.at(i),data.at(location))){
            location=i;
        }
    }
    data.erase(data.begin()+location);
    return;
}

template<typename TYPE, typename COMP>
const TYPE& poorman_heap<TYPE, COMP>::top() const {
    int location=0;
    for(int i=1;i<data.size();i++){
        if(this->compare(data.at(i),data.at(location))){
            location=i;
        }
    }
    return data.at(location); 
}

P.S. greater is

struct greater{
    bool operator()(int x,int y){
        return x>y;
    }
}

Upvotes: 1

Views: 130

Answers (2)

Ben S.
Ben S.

Reputation: 1143

It looks like the problem is that the compare member has operator() declared as a non-const function. Since it sounds like you don't have the ability to change that, you might be able to get the behavior that you want by declaring it as a mutable member in poorman_heap.

The mutable keyword lets you distinguish between an object being "physically const" (meaning the actual bytes don't change and being "logically const" (meaning the bytes might change but the value of the object isn't different in a fundamental sense). Basically it means that something "doesn't count" for the purposes of const-ness. The classic example in my mind is lazy initialization - you want to declare the get_value() function on a class const, but you also don't want to waste time computing the value if no one uses it, so you declare the value mutable and now you're allowed to calculate it and assign to it inside get_value() even though it is a const member function.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227578

Make the call operator of greater a const operator:

struct greater
{
    bool operator()(int x,int y) const
    {
        return x>y;
    }
}

The same applies to whatever this->compare resolves to. It needs to be const.

It doesn't make much sense for a comparator to be non-const.

Upvotes: 1

Related Questions