
PriorityQueue의 compare 메서드를 오버라이딩하는 방법은 다음과 같습니다.
#hostingforum.kr
php
class MyObject implements Comparable {
private $value;
public function __construct($value) {
$this->value = $value;
}
public function compareTo(MyObject $other) {
if ($this->value < $other->value) {
return -1; // this 객체가 우선순위가 높다
} elseif ($this->value > $other->value) {
return 1; // other 객체가 우선순위가 높다
} else {
return 0; // 값이 같음
}
}
}
위 예제에서, MyObject 클래스는 PriorityQueue에서 사용할 객체입니다. compareTo 메서드는 두 개의 MyObject 객체를 비교하고, return 값은 다음과 같이 해석됩니다.
* -1: this 객체가 우선순위가 높다
* 0: 값이 같음
* 1: other 객체가 우선순위가 높다
이러한 compareTo 메서드를 오버라이딩하면, PriorityQueue는 두 개의 객체를 비교할 때 이 메서드를 호출합니다.
#hostingforum.kr
php
$queue = new SplPriorityQueue();
$queue->insert(new MyObject(5, 5);
$queue->insert(new MyObject(3, 3);
$queue->insert(new MyObject(8, 8);
while ($queue->valid()) {
echo $queue->extract()->value . "n";
}
위 예제에서, PriorityQueue는 MyObject 객체를 우선순위에 따라 추가하고, 가장 높은 우선순위를 가진 객체를 먼저 추출합니다.
이러한 compareTo 메서드를 오버라이르는 경우, PriorityQueue는 객체를 우선순위에 따라 추가하고, 가장 높은 우선순위를 가진 객체를 먼저 추출합니다.
2025-04-11 23:49