1

I am trying to copy a std::vector into std::priority_queue while the following two approaches are working.

vector<int> parts = { 8, 4, 6, 12, 57, 28};                          //source
priority_queue<int, vector<int>, greater<int>> minHeap;              //target

approach 1:

all_of(parts.begin(), parts.end(), [&minHeap](int& part){minHeap.push(part); return true;});

approach 2:

for(int& part: parts) minHeap.push(part);

However, I'd like to know if the same can be done by std::copy?

dixit_chandra
  • 468
  • 3
  • 14
  • 4
    Why not use the constructor? `priority_queue, greater> minHeap(parts.begin(), parts.end());` ? – fabian Jun 08 '21 at 19:02
  • 1
    surprisingly I didn't think of the constructor. thanks for enlightening me. – dixit_chandra Jun 08 '21 at 19:06
  • Possible duplicate https://stackoverflow.com/questions/4115431/inserters-for-stl-stack-and-priority-queue – Galik Jun 08 '21 at 19:11
  • 1
    `std::all_of()` is not intended for this work - it is intended to check if a condition is true for all elements. It might work for you, but would be confusing for the readers. If you want an algorithm here, use `std::for_each()` - but it no better in this case than `for` loop. – Eugene Jun 08 '21 at 19:55
  • @Eugene yeah I know it was a tweak. – dixit_chandra Jun 09 '21 at 08:16

1 Answers1

3

Yes, it can be done with std::copy(), but only if you write (or find) a custom OutputIterator that calls the queue's push() method when the iterator is written to. The standard library has no such iterator built-in for calling push() (but it has std::front_insert_iterator for push_front(), std::back_insert_iterator for push_back(), std::insert_iterator for insert(), etc).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770