더북(TheBook)

첫 번째 템플릿 타입 인수는 저장할 원소의 타입이고, 두 번째는 원소를 저장할 컨테이너 타입, 세 번째는 원소를 비교할 함수 객체의 타입을 지정한 것이다. 람다 표현식의 타입이 기본 비교 타입 std::less<T>와 다르기 때문에 세 번째 템플릿 타입 인수를 지정해야 한다.

포인터를 저장하는 priority_queue 초기화에 외부 컨테이너를 지정하는 것도 가능하다.

std::vector<shared_ptr<string>> init {std::make_shared<string>(“one”),
                        std::make_shared<string>(“two”),
                        std::make_shared<string>(“three”),
                        std::make_shared<string>(“four”)};
std::priority_queue<shared_ptr<string>, std::vector<shared_ptr<string>>, decltype(comp)>
                                                                              words(comp, init);

init 벡터는 make_shared<string>()을 호출해 생성한 초깃값을 갖고 있다. 우선순위 큐 생성자에 지정된 인수는 원소들을 어떻게 비교할지 정의한 객체와 원소를 초기화할 원본을 담고 있는 컨테이너다. vector에 저장된 스마트 포인터는 우선순위 큐 words를 초기화하기 위해 복제되어 사용된다. 물론, 다른 컨테이너의 원소로 우선순위 큐를 초기화할 때는 unique_ptr<string> 원소를 사용할 수 없게 된다. 반드시 shared_ptr<string>을 사용해야 한다.

초기 원소 세트를 유지할 필요가 없다면 priority_queue 객체의 emplace() 멤버를 호출해 컨테이너 내부에서 바로 생성하는 것도 가능하다.

std::priority_queue<shared_ptr<string>, std::vector<shared_ptr<string>>, decltype(comp)>
                                                                              words1 {comp};
words1.emplace(new string {“one”});
words1.emplace(new string {“two”});
words1.emplace(new string {“three”});
words1.emplace(new string {“five”});
 

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.