티스토리 뷰

PS

1181 단어 정렬

Eastplanet 2021. 1. 9. 00:49
더보기

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

<를 >로 바꾸어 주면 내림차순으로 바뀌게된다

'PS' 카테고리의 다른 글

2609 최대공약수와 최소공배수  (0) 2021.01.09
1920 수 찾기  (0) 2021.01.09
1018 체스판 다시 칠하기  (0) 2021.01.08
1550 16진수  (0) 2021.01.08
10757 큰수 A+B  (0) 2021.01.08
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/01   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함