我试图记录 while 循环运行了多少次。但是,代码是给我的,我不确定以哪种方式修改代码才能增加代码。
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;
}
Run Code Online (Sandbox Code Playgroud)
当我编译这个时,我得到“incrementCounter无法修改,因为它是通过const对象访问的”
当我看到这个时,我知道我无法编辑 const 函数中的值,但我不知道该怎么做。
声明incrementCounter如下mutable:
mutable int incrementCounter;
Run Code Online (Sandbox Code Playgroud)
然后您就可以在findPos函数中更改它。
mutable -
适用于非引用非常量类型的非静态类成员,并指定该成员不会影响类的外部可见状态(通常用于互斥体、备忘录缓存、惰性求值和访问检测)。mutableconst 类实例的成员是可修改的。
(注意:C++ 语言语法将 mutable 视为存储类说明符,但它不影响存储类。)