问题
I was wondering how SplPriorityQueue
works when priority is string
or int
. Quick example:
$queue = new \SplPriorityQueue();
$queue->insert('b', 5);
$queue->insert('c', 5);
$queue->insert('d', 1);
$queue->insert('a', 10);
$queue->insert('1', 'a');
$queue->insert('2', 'b');
print_r($queue);
Output:
Array
(
[5] => a
[4] => b
[3] => c
[2] => d
[1] => 2
[0] => 1
)
Question: why items with int
priority are listed first (i.e. a b c d)? When priority is string
(items 1 2), is b
considered greater than a
?
回答1:
This is determined by SplPriorityQueue::compare(). The documentation states about its return value:
Result of the comparison, positive integer if priority1 is greater than priority2, 0 if they are equal, negative integer otherwise.
Note:
Multiple elements with the same priority will get dequeued in no particular order.
Note, that the parameters priority1 and priority2 are declared as mixed
and there is no mention of converting to int.
This means, the usual rules for >
apply (see comparison operator documentation):
- string compared to string: lexical comparison (numerical if both strings are numerical)
- int compared to int: numerical comparison
- string compared to int: string is converted to number, numerical comparison
(int)'a'
and (int)'b'
resolves to 0
, this is why these items come last after all numbers.
These are the relevant comparisons for your example:
php > var_dump(1 > 'a');
bool(true)
php > var_dump(1 > 'b');
bool(true)
php > var_dump('b' > 'a');
bool(true)
来源:https://stackoverflow.com/questions/15851726/how-splpriorityqueue-works-when-priority-is-not-an-integer