更改优先级队列元素是否会导致重新使用队列?

2022-01-21 00:00:00 queue priority-queue c++ stl

我有一个priority_queue,我想修改它的一些内容(优先级值),那么队列会被重新使用吗?

I have a priority_queue, and I want to modify some of it's contents (the priority value), will the queue be resorted then?

这取决于它是使用 push/pop(更有可能,因为您只需要插入",而不是使用整体),还是在访问 top 或 pop 时.

It depends if it resorts on push/pop (more probable, becouse you just need to "insert", not resort whole), or when accessing top or pop.

我真的很想更改队列中的一些元素.类似的东西:

I really want to change some elements in the queue. Something like that:

priority_queue<int> q;

int a=2,b=3,c=5;
int *ca=&a, *cb=&b, cc=&c;

q.push(a);
q.push(b);
q.push(c); //q is now {2,3,5}

*ca=4;

//what happens to q?
// 1) {3,4,5}
// 2) {4,2,5}
// 3) crash

推荐答案

priority_queue 复制你推入其中的值.您最后的分配将对优先级队列的顺序产生零影响,也不会对其中存储的值产生影响.

priority_queue copies the values you push into it. Your assignment at the end there will have zero effect on the order of the priority queue, nor the values stored inside of it.

相关文章