[英]How to preallocate(reserve) a priority_queue<vector>?
How can I preallocate a std::priority_queue
with a container of type std::vector
?如何使用
std::vector
类型的容器预分配std::priority_queue
?
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?是否可以使用
priority_queue
的构造函数将其包装在预先保留的向量周围?
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.您也可以使用邪恶的恶作剧来访问受保护的成员,但我不建议这样做。
Another solution might be to make your own class derived from std::priority_queue, such as:另一种解决方案可能是使您自己的类从 std::priority_queue 派生,例如:
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 对象:
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;
In general with C++11
you can write a make_reserved
function as below.通常,使用
C++11
您可以编写如下的make_reserved
函数。
#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;
}
I don't have enough reputation to comment on Mike Seymour's post, but he ommited the third template argument of std::priority_queue
:我没有足够的声誉来评论 Mike Seymour 的帖子,但他省略了
std::priority_queue
的第三个模板参数:
std::vector<unsigned char> container;
container.reserve(1024);
std::priority_queue<unsigned char, std::vector<unsigned char>, std::less<unsigned char>> pq(std::less<unsigned char>(), std::move(container));
It is quite verbose for sure, but it does the work.它确实很冗长,但它确实有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.