![](/img/trans.png)
[英]priority_queue<vector<int> > pq; is saything that “priority_queue” is not a template, how would I fix this?
[英]How to preallocate(reserve) a priority_queue<vector>?
如何使用std::vector
類型的容器預分配std::priority_queue
?
std::priority_queue<unsigned char, std::vector<unsigned char>> pq;
pq.c.reserve(1024);
不編譯,因為底層向量是受保護的成員。 是否可以使用priority_queue
的構造函數將其包裝在預先保留的向量周圍?
另一種解決方案可能是使您自己的類從 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);
}
};
然后,在代碼中,以這種方式創建一個 MyPQueue 對象:
MyPQueue mpq(1024);
哪個對象可以在需要時向上轉換回基類。
std::priority_queue<unsigned char, std::vector<unsigned char>>& pq = mpq;
通常,使用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;
}
我沒有足夠的聲譽來評論 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));
它確實很冗長,但它確實有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.