Alex Bollbach
Alex Bollbach

Reputation: 4570

Initializing a vector with a priorityqueue

I have found code similar to the following in a book about algorithms. The code attempts to initialize a vector from the current state of a max_heap. However, the following code in Xcode (7.3) yields the compile-time error:

No Matching Constructor for initialization of 'vector'

// declaring priority queue
priority_queue<Star, vector<Star>> max_heap;


// pushing/popping to/from heap

// initializing vector with heap
vector<Star> closestStars(max_heap);

Either the book is in error or I am doing something incorrectly. In the former case, is there a correct way to initialize a vector from the underlying container of an STL priority queue?

Upvotes: 0

Views: 1005

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

The book probably assumes that priority_queue is a subclass of std::vector.

The C++ standard does not guarantee that.

Once constructed, priority_queue provides no public access to the underlying container, hence you cannot initialize a std::vector from it.

However, what you can do, apparently, is to subclass your std::priority_queue, with the subclass apparently having access to the inherited protected member c, which should be the underlying std::vector, that you can use to copy-construct another vector.

Upvotes: 3

Related Questions