https://programmers.co.kr/learn/courses/30/lessons/12915
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int N;
bool compare_c(string a, string b) {
if (a.at(N) != b.at(N)) return a.at(N) < b.at(N);
else return a < b;
}
vector<string> solution(vector<string> strings, int n) {
vector<string> answer;
N = n;
sort(strings.begin(), strings.end(), compare_c);
answer = strings;
return answer;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
algorithm 라이브러리의 sort() 함수를 활용해 풀 수 있었다.
sort() 다양한 사용법 중 3번째 인자로 사용자가 정의한 비교함수를 넣어 사용할 수 있는 것을 알면 쉽게 풀 수 있음
n번째 인덱스 원소의 사전적 순서로 비교하는 사용자 정의 함수 compare_c 를 정의하여 sort()에 넣어주었다
sort() → algorithm 라이브러리에 정의된 함수로 기본적으로 Quick sort 알고리즘을 사용한다
1. template <class RandomIt>
sort(RandomIt begin, RandomIt end)
→ begin에서부터 end까지의 반복자 범위 내 원소들을 오름차순 정렬해준다.
기본적으로 operator< 를 이용해 원소들을 비교
2. template <class RandomIt, class Compare>
sort(RandomIt begin, RandomIt end, Compare cmp)
→ begin에서부터 end까지의 반복자 범위 내 원소들을 오름차순 정렬해준다.
cmp 비교함수를 사용해 비교하여 원소들을 비교 (사용자 정의 함수도 사용 가능)
비교함수의 반환값은 boolean 타입으로 true일 경우 앞의 원소가 먼저 정렬된다
* sort()의 사용법은 몇 개 더 있지만 두 가지만 정리해 두었습니다.
'알고리즘(C++) > 프로그래머스 level1' 카테고리의 다른 글
서울에서 김서방 찾기 (0) | 2020.04.01 |
---|---|
문자열 내림차순으로 배치하기 (0) | 2020.04.01 |
나누어 떨어지는 숫자 배열 (0) | 2020.03.30 |
가운데 글자 가져오기 (0) | 2020.03.30 |
K번째수 (0) | 2020.03.30 |