✅ priority_queue ✅ sort custom
위 문제에서 4문장을 배열로 담아 sort하면 되지만 다시 sort 하는게 귀찮아 priority_queue을 사용했는데 priority_queue의 정렬을 커스텀 하는게 sort함수와 다르다는 것을 알게 되었다.
결론 부터 말하면
operator() 연산자를 원하는대로 오버로딩, 이를 구조체로 감싸줌으로써 custom sort을 해야한다.
sort는 bool cmp() 함수만 새로 만들어주면 되었지만
priority_queue는 cmp 구조체의 operator() 연산자를 오버로딩 해줘야 한다.
그 이유는 https://my-codinglog.tistory.com/21 에 잘 정리가 되어 있다.
따라서 위 문제를 priority_queue로 풀어본 결과는 다음과 같다.
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
using namespace std;
struct cmp{
bool operator()(string a, string b){
return a.length() > b.length();
}
};
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
priority_queue<string, vector<string>, cmp> que;
for(int i=0;i<4;i++){
string str;
cin >> str;
que.push(str);
}
while(!que.empty()){
cout << que.top() << "\n";
que.pop();
}
return 0;
}