https://school.programmers.co.kr/learn/courses/30/lessons/12915
sort할 때 compare 함수를 잘 이용해야 할 문제인거 같아서 만들었다. 숫자n은 전역변수로 넘겨주었다.
인덱스에 해당하는 글자가 같으면 입력된 문자열 전체를 비교하였고 아니면 해당 인덱스의 글자로만 크기를 비교했다.
comp함수 만들 때 <인가 >인가를 잘 생각해서 구현하자. 1번입력과 2번입력중 2번이 큰 경우는 오름차순 1번이 큰 경우는 내림차순
s1 < s2 : 오름차순
s1 > s2 : 내림차순
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int num = 0;
bool cmp(string& s1, string& s2)
{
if(s1[num] == s2[num])
return s1 < s2;
return s1[num] < s2[num];
}
vector<string> solution(vector<string> strings, int n) {
num = n;
sort(strings.begin(),strings.end(), cmp);
return strings;
}
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int i;
bool compare (string a, string b) {
return a[i] == b[i] ? a < b : a[i] < b[i];
}
vector<string> solution(vector<string> strings, int n) {
i = n;
sort (strings.begin(), strings.end(), compare);
return strings;
}
compare에서 삼항연산자를 사용하였다.