Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modifying a private int in a const function issue

My code is below and i am having an error with numberCollisions += collisionNum; The error states, 'numberCollisions' cannot be modified because it is being used through a const object. Is this error just popping up because it is a const function? Thanks for the help.

int HashTable_qp::findPos( const string & x ) const
{
    /* 1*/      int collisionNum = 0;
    /* 2*/      int currentPos = myhash( x, array.size( ) );

    /* 3*/      while( array[ currentPos ].info != EMPTY &&
        array[ currentPos ].element != x )
    {
        /* 4*/          currentPos += 2 * ++collisionNum - 1;  // Compute ith probe
        /* 5*/          if( currentPos >= array.size( ) )
            /* 6*/              currentPos -= array.size( );
    }
    numberCollisions += collisionNum;
    /* 7*/      return currentPos;
}
like image 338
user1074798 Avatar asked Jan 18 '26 09:01

user1074798


2 Answers

Yes -- for something like this where you're modifying an internal bookkeeping number that doesn't affect the logical state of the object, you may want to consider defining the variable with the mutable qualifier:

class HashTable_op { 
    mutable int numberCollisions;

};
like image 135
Jerry Coffin Avatar answered Jan 20 '26 21:01

Jerry Coffin


Yes, exactly because of this reason. Constant method implies you won't change the instance, but you do, since your findPos is supposed to change the instance. So just remove const and move on.

like image 22
Roman Byshko Avatar answered Jan 20 '26 22:01

Roman Byshko