Search code examples
c++vectorpriority-queuereinterpret-cast

Is reinterpret_cast on priority_queue to iterate through the underlying vector non-standard?


The following piece of code compiles and runs just fine, but I have been reading up on reinterpret_cast and I can't really make out if it's standard compliant and is portable. In my head it should be since we explicitly specify the underlying container of the priority_queue but I haven't been able to get a straight answer so SO-wizards might have some insight into this piece.

What it does is basically create a priority_queue that deals with integers using a vector. It then reinterpret_cast's that queue into a vector-pointer so that the elements of the queue can be iterated over (since priority_queue does not include that functionality itself).

#include <iostream>
#include <vector>
#include <queue>


int main() {
    std::priority_queue< int, std::vector<int> > pq;

    pq.push(100);
    pq.push(32);
    pq.push(1);

    auto o = reinterpret_cast<std::vector<int> *>(&pq);
    for (std::vector<int>::iterator it = (*o).begin(); it != (*o).end(); it++) {
        std::cout << (*it) << std::endl;
    }

    return 0;
}

Solution

  • The standard makes no guarantees about the layout of the std::priority_queue class. If this works on your implementation, it must be because the std::vector is stored at the beginning of the std::priority_queue object, but this certainly cannot be relied upon.

    The proper thing to do is write your own variant of std::priority_queue (the <algorithm> header already contains the necessary heap algorithms, such as std::push_heap) or to derive a class from std::priority_queue, which gives you access to the protected member c which refers to the underlying container.