더북(TheBook)

원소들을 반대로 정렬하고 싶을 때, 즉 가장 작은 객체가 우선순위 큐의 앞에 오게 하고 싶다면 세 가지 템플릿 타입 인수를 모두 지정해야 한다.

std::string wrds[] {"one", "two", "three", "four"};
std::priority_queue<std::string, std::vector<std::string>, std::greater<std::string>>
            words1 {std::begin(wrds), std::end(wrds)}; // "four" "one" "three "two"

이 문장은 범위에 있는 string 객체를 operator>() 함수로 비교하면서 우선순위 큐를 생성한다. 따라서 앞에서 생성한 words 우선순위 큐와는 반대 순서가 된다.

우선순위 큐는 front(), push_back(), pop_back(), size(empty() 함수 멤버를 지원하는 컨테이너를 사용할 수 있다. 이러한 함수 멤버를 지원하는 컨테이너로는 deque가 있으므로 vector 대신 deque를 쓸 수도 있다.

std::string wrds[] {"one", "two", "three", "four"};
std::priority_queue<std::string, std::deque<std::string>> words {std::begin(wrds),
std::end(wrds)};

words 우선순위 큐는 wrds 배열의 string 객체를 기본 비교 조건자로 우선순위를 비교해 deque 컨테이너에 저장한다. 따라서 string 객체의 순서는 앞서 words1과 같다. priority_queue 생성자는 두 번째 타입 인수에 지정된 타입으로 원소를 저장할 순차열 컨테이너를 생성하고, 이는 priority_queue 객체의 내부 클래스가 된다.

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