gpt4 book ai didi

c++ - 堆变量作用域

转载 作者:太空宇宙 更新时间:2023-11-04 15:15:51 24 4
gpt4 key购买 nike

我正在实现一个堆,但我无法理解为什么变量“int hole”不在我的插入方法的范围内。例如,我尝试了很多事情,在方法和类中声明它。我的插入中的 for 循环是引发错误的原因。

template <class Comparable>
class BinaryHeap
{
public:
explicit BinaryHeap( int capacity = 100 );
bool isEmpty( ) const;
bool isFull( ) const;
const Comparable & findMin( ) const;
void insert( const Comparable & x );
void deleteMin( );
void deleteMin( Comparable & minItem );
void makeEmpty( );
private:
int currentSize; // Number of elements in heap
vector<Comparable> array; // The heap array
void buildHeap( );
void percolateDown( int hole );
};

template <class Comparable>
void BinaryHeap<Comparable>::insert( const Comparable & x )
{
if( isFull( ) ) //throw Overflow( );
// Percolate up
int hole = ++currentSize;
**for( ; hole > 1 && x < array[ hole / 2 ]; hole /= 2 )**
array[ hole ] = array[ hole / 2 ];
array[ hole ] = x;
}

最佳答案

throw 被注释掉后,if 语句看起来像

if( isFull( ) )
{
int hole = ++currentSize;
}

变量 hole 仅在 if 语句内“在范围内”。

关于c++ - 堆变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33438712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com