请求Java/C++官方文档中关于优先队列比较器不变性的说明
Java 示例问题重现
int[] a = new int[]{1, 2}; PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Comparator.comparingInt(i -> a[i])); pq.add(0); pq.add(1); a[1] = 0; System.out.println(pq.peek()); // 输出 0
向优先队列插入元素后,修改了影响比较器判断的外部数组a,导致元素的相对比较顺序反转,但优先队列并未自动调整结构,最终行为未定义——这是实现Dijkstra算法时的典型错误,违反了队列中元素的比较结果必须保持不变直到被移除的隐含约定。
Java 官方文档相关说明
Java PriorityQueue类的官方文档明确提及了该类的行为限制:
注意:如果元素在队列中时被修改,且修改会影响它们的比较顺序,那么优先队列的行为是未定义的。队列的排序不会自动更新。
对应的英文原文:
Caution: If elements are modified in a way that affects their comparison order while they are in the queue, the queue's ordering will not be updated automatically. The behavior of a priority queue is undefined if elements are modified in a way that affects their comparison order while they are in the queue.
C++ 官方文档相关说明
C++ 标准库中std::priority_queue的权威文档明确了该限制:
注意:如果元素在优先队列中时被修改,除非修改不改变它与其他任何元素的相对顺序,否则行为是未定义的。
对应的英文原文:
Note: If the value of an element is modified while it is in the priority queue, the behavior is undefined unless the modification does not change its relative ordering with any other element.
内容的提问来源于stack exchange,提问作者Dmitry

