You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There is an issue that has bothered me for a long time. In order to extract the top element from std::priority_queue, we have to write something like this:
auto x = queue.top(); // Copy constructor or copy assignment.
queue.pop();
Unfortunately, we cannot move a top value from the queue because top() is of const_reference type (https://eel.is/c++draft/priority.queue#priqueue.members) . This can cause a performance hit if the value type is expensive to copy (large strings, etc.).
The idea is to provide something like a pop(T&) method overload:
// Implementation example. noexcept-based computations and choices are omitted.
template <typename U>
void pop(U& to) {
to = std::move(container.front());
pop();
}
// Usage:
T x; // or std::optional<T>
queue.pop(x); // move if T::operator=(T&&) is noexcept
Alternative interface:
T extract_top() {
T val = std::move(container.front());
pop();
return val;
}
I like it even more than the first one.
The text was updated successfully, but these errors were encountered:
a-sid
changed the title
Add an ability to move elements from std::priority_queue
Add an ability to move the top element from std::priority_queue
Feb 24, 2025
It is also a bit unclear how priority_queue is expected to work with non-copyable types without such an ability. We can move elements in but not out of the queue.
There is an issue that has bothered me for a long time. In order to extract the top element from
std::priority_queue
, we have to write something like this:Unfortunately, we cannot move a top value from the queue because
top()
is ofconst_reference
type (https://eel.is/c++draft/priority.queue#priqueue.members) . This can cause a performance hit if the value type is expensive to copy (large strings, etc.).The idea is to provide something like a
pop(T&)
method overload:Alternative interface:
I like it even more than the first one.
The text was updated successfully, but these errors were encountered: