How to preallocate(reserve) a priority_queue<vector>?

若如初见. 提交于 2020-01-11 00:06:57

问题


How can I preallocate a std::priority_queue with a container of type std::vector?

std::priority_queue<unsigned char, std::vector<unsigned char>> pq;
pq.c.reserve(1024);

Does not compile because the underlying vector is a protected member. Is it possible to use the constructor of the priority_queue to wrap it around a pre-reserved vector?


回答1:


Yes, there's a constructor for that. It's slightly tedious that you also have to specify a comparator:

std::vector<unsigned char> container;
container.reserve(1024);
std::priority_queue<unsigned char, std::vector<unsigned char>> pq (
    std::less<unsigned char>(), std::move(container));

You can also use evil shenanigans to access the protected member, but I wouldn't recommend it.




回答2:


Another solution might be to make your own class derived from std::priority_queue, such as:

class MyPQueue : public std::priority_queue<unsigned char, std::vector<unsigned char>>
{
public:
    MyPQueue(size_t reserve_size)
    {
        this->c.reserve(reserve_size);
    }
};

then, in the code, create a MyPQueue object in this way:

MyPQueue mpq(1024);

which object can be upcasted back to the base class whenether needed.

std::priority_queue<unsigned char, std::vector<unsigned char>>& pq = mpq;



回答3:


In general with C++11 you can write a make_reserved function as below.

#include <vector>
#include <iostream>
#include <utility>
#include <functional>

template <class T>
std::vector<T> make_reserved(const std::size_t n)
{
  std::vector<T> v;
  v.reserve(n);
  return v;
}

int main()
{
  using Q = std::priority_queue<int, std::vector<int>>;
  auto q = Q(std::less<int>(), make_reserved<int>(100));
  std::cout << q.size() << std::endl;
}


来源:https://stackoverflow.com/questions/29235978/how-to-preallocatereserve-a-priority-queuevector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!