Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an ability to move the top element from std::priority_queue #607

Open
a-sid opened this issue Feb 24, 2025 · 1 comment
Open

Add an ability to move the top element from std::priority_queue #607

a-sid opened this issue Feb 24, 2025 · 1 comment

Comments

@a-sid
Copy link

a-sid commented Feb 24, 2025

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.

@a-sid 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
@a-sid
Copy link
Author

a-sid commented Feb 26, 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant