1181 단어 정렬
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool compare(string a, string b) {
if(a.length()==b.length())return a<b;
return a.length() < b.length();
}
int main() {
vector <string> a;
int count;
cin >> count;
for (int i = 0; i < count; i++) {
string temp;
cin >> temp;
a.push_back(temp);
}
sort(a.begin(), a.end(), compare);
string temp;
for (int i = 0; i < count; i++) {
if (temp == a[i])continue;
cout << a[i]<<endl;
temp = a[i];
}
}
단어들을 입력받아 중복을 제거하고 길이순, 사전순으로 나열하는 문제이다
중복을 제거하고 길이비교까진 했으나 정렬을 할줄 모르겠어서 검색을 했다.
sort(시작,끝,형식)을 사용하기위해 string 이아닌 vector <string> 을 사용하고
sort에서는 단어의 길이를 비교해주지 않기 때문에 compare사용자 정의함수를 만들어서
길이까지 비교해주는 형식을 만들어서 사용한다.
compare 함수에서
return a<b;
return a.length()<b.length();
<를 >로 바꾸어 주면 내림차순으로 바뀌게된다