函式名:SplHeap::current()
適用版本:所有PHP版本
函式描述:SplHeap::current()方法用於獲取當前指標位置的元素值。
用法:
public function current (): mixed
示例:
// 建立一個繼承SplHeap的自定義堆類
class MyHeap extends SplHeap {
// 實現抽象方法,定義元素比較規則
protected function compare($value1, $value2) {
return $value1 - $value2;
}
}
// 建立堆物件
$heap = new MyHeap();
// 向堆中新增元素
$heap->insert(5);
$heap->insert(3);
$heap->insert(8);
// 迴圈遍歷堆中的元素
foreach ($heap as $value) {
echo $heap->current() . PHP_EOL; // 獲取當前元素值
$heap->next(); // 指標移動到下一個元素
}
輸出結果:
8
5
3
注意事項:
- SplHeap::current()方法只能在使用foreach迴圈遍歷SplHeap物件時使用。
- 在迴圈內部使用SplHeap::current()方法時,確保呼叫該方法之前已經呼叫了SplHeap::next()方法,使指標移動到下一個元素位置。
- 使用SplHeap::current()方法之前,需要確保SplHeap物件中有有效的元素。