Reputation: 81
I'm attempting to keep a counter of how many times a while loop is run through. However, the code was given to me, and I'm not sure which way to modify the code to be able to increment the code.
int findPos( const HashedObj & x ) const
{
int offset = 1;
int currentPos = myhash( x );
while( array[ currentPos ].info != EMPTY &&
array[ currentPos ].element != x )
{
currentPos += offset; // Compute ith probe
offset += 2;
incrementCounter++;
if( currentPos >= array.size( ) )
currentPos -= array.size( );
}
return currentPos;
}
When I compile this, I get "incrementCounter cannot be modified because it is being accessed through a const object"
When I see this, I know that I can't edit a value in a const function, but I'm not sure how to do this.
Upvotes: 0
Views: 1071
Reputation: 26800
Declare incrementCounter
as mutable
like this:
mutable int incrementCounter;
Then you will be able to change it in the findPos
function.
mutable -
applies to non-static class members of non-reference non-const type and specifies that the member does not affect the externally visible state of the class (as often used for mutexes, memo caches, lazy evaluation, and access instrumentation).mutable
members of const class instances are modifiable.
(Note: the C++ language grammar treats mutable as a storage-class-specifier, but it does not affect storage class.)
Upvotes: 5