본문 바로가기

C++

[C++] Sort 사용법 & Compare 함수

python만 쓰다가 c++으로 정렬하려니 머리가 아파와서 기록이라도 하고자합니다 하하..

[C++] Sort 

먼저 C++의 sort는 O(nlogn) 의 복잡도를 가지는 Intro Sort를 사용하였다고 합니다.

Sort를 사용하려면 #include <algorithm>를 추가하시고, 인자는 아래와 같이 사용하시면 됩니다..

#include <algorithm>

void sort (RandomAccessIterator first, RandomAccessIterator last);

void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

first와 last는 sort할 범위를 나태는 인자입니다.

만약 int[] arr = {5,1,2,4,3}를 정렬하고자 한다면 아래와 같이 사용하면 되는 것이죠.

sort(arr.begin(), arr.end())

Compare

Compare가 추가된 sort는 정렬방식에 조건을 추가하여 정렬하고 싶을 때 사용합니다.

Python으로 보면 key = lmabda k 와 같은 것이죠.

아래는 프로그래머스의 [문자열 내마음대로 정렬하기] 문제를 풀이한 코드입니다.

#include <string>
#include <vector>
#include <algorithm>

using namespace std;
int idx;

bool compare(string a, string b) {
    return a[idx]==b[idx] ? a<b : a[idx]<b[idx];
}

vector<string> solution(vector<string> strings, int n) {
    idx = n;
    sort(strings.begin(), strings.end(), compare);
    return strings;
}