2015-03-24 18 views

Odpowiedz

5

Tak, do tego jest constructor. Jest to nieco uciążliwe, że trzeba także określić komparatora:

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)); 

Można również użyć evil shenanigans aby uzyskać dostęp do elementu chronionego, ale nie polecam go.

3

Innym rozwiązaniem mogłoby być tworzyć własne klasy pochodzące z std :: priority_queue, takich jak:

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

następnie w kodzie utworzyć obiekt MyPQueue w ten sposób:

MyPQueue mpq(1024); 

który obiekt może zostać przesunięty z powrotem do klasy podstawowej, jeśli jest potrzebny.

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

Ogólnie w C++11 można napisać make_reserved funkcję jak poniżej.

#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 std::move(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; 
} 
Powiązane problemy