프로그래머스 lv1. 문자열 내마음대로 정렬하기
//<utiltiy> 헤더가 필요하나, <algorithm>, <vector>헤더 파일 안에 포함되어있음
#include <vector>
pair<int, int> p;
pair<int, double>;
pair<string, char>;
p.first // 첫번째 인자를 조회한다.
p.second //두번째 인자를 조회한다.
make_pair() //pair를 만들어 반환한다.
bool cmp (const pair<int, int> a, const pair<int, int> a){
// second 값을 기준으로 뒤에 값이 더 크면 true를 반환한다. (오름차순 정렬에 사용 가능)
if (a.second<=b.second) return true;
else false;
}
//pair를 포함한 벡터를 선언
vector<pair<int, int>> vec;
vec.push_back(make_pair(a,b));
상단에 작성한 cmp 함수를 기준으로 벡터를 정렬한다.
sort(vec.begin(), vec.end(), cmp);
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(const pair<string, int> a, const pair<string, int> b ){
//index 문자를 기준으로 정렬한다.
if (a.second<b.second) return true;
// 두 문자가 같은 경우 문장을 기준으로 정렬한다.
else if (a.second==b.second) return a.first<b.first;
return false;
}
vector<string> solution(vector<string> strings, int n) {
vector<string> answer;
vector<pair<string, int>> arr;
for (int i=0; i<strings.size(); i++){
arr.push_back(make_pair(strings[i],strings[i][n]));
}
sort(arr.begin(), arr.end(),cmp);
for (int i=0; i<arr.size(); i++){
answer.push_back(arr[i].first);
}
return answer;
}
참고한 블로그
https://chanhuiseok.github.io/posts/algo-52/
https://ya-ya.tistory.com/91
https://godog.tistory.com/entry/c-vector-and-pair-%EC%82%AC%EC%9A%A9