-
C++ sort함수 cmp 함수유용한 정보 2021. 10. 8. 23:56반응형
C++ STL 중 algorithm 헤더를 사용할 경우 sort() 함수를 사용할 수 있습니다.
해당 함수의 사용법과 독자적으로 만든 cmp 함수를 사용하여 다른 sorting을 하는 방법을 알아보겠습니다.
SORT
#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int arr[5] = {1, 10, 100, 2, 4}; vector<int> arr2 = {1, 10, 100, 2, 4}; sort(arr, arr+5 ); sort(arr2.begin(), arr2.end()); cout << "배열 arr : "; for(int tmp : arr) cout<<tmp<<" "; cout << "\n배열 arr2 : "; for(int tmp : arr2) cout<<tmp<<" "; return 0; }
실행화면 int형 배열 arr와 int형 vector arr2의 sorting 결과입니다.
sort함수는 오름차순으로 작은 수부터 큰 수의 순서로 점차 커지는 것을 확인 할 수 있습니다.
sort( 시작주소, 끝나는 주소, default) ;
위와 같은 기본 형식을 따르고 있습니다.
#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int arr[5] = {1, 10, 100, 2, 4}; vector<int> arr2 = {1, 10, 100, 2, 4}; sort(arr, arr+5 , greater<int>()); sort(arr2.begin(), arr2.end(), less<int>()); cout << "배열 arr : "; for(int tmp : arr) cout<<tmp<<" "; cout << "\n배열 arr2 : "; for(int tmp : arr2) cout<<tmp<<" "; return 0; }
greater <자료형>()와 less <자료형>()을 사용하여 내림차순과 오름차순을 표현할 수 있습니다.
3번째 인자의 경우, 원하는 함수를 만들어 원하는 형식으로 sorting 할 수 있습니다.
cmp함수 생성법
struct boxer { int weight=0; double rateW=0.00; int numW=0;//본인보다 무거운 애들 때린 횟수 int num=0; }; bool cmp(const boxer &B1, const boxer &B2) { if(B1.rateW > B2.rateW) { return true; } if(B1.rateW == B2.rateW) { if(B1.numW > B2.numW) { return true; } if(B1.numW == B2.numW) { if(B1.weight > B2.weight) { return true; } if(B1.weight == B2.weight) { if(B1.num < B2.num) { return true; } } } } return false; }
이와 같이 필요한 구조체를 생성한 후 구조체를 비교하는 cmp함수를 생성하여 sorting 함수에 사용할 수 있습니다.
cmp 함수를 만드는 경우에 참조형 변수로 만드는 경우가 더 안전한 것으로 보입니다. (구조체인 경우)
실제 사용 예는 아래와 같습니다.
sort(arr.begin(), arr.end(), cmp);
반응형'유용한 정보' 카테고리의 다른 글
C++ map STL 사용법 (0) 2021.12.05 string split 하는법 C++ | sstream 사용법 C++ | find함수 substr함수 (0) 2021.12.02 pair형 vector 정렬하기 / vector<pair< a, b>> sort /compare, greater, less (0) 2020.07.23 DFS, BFS code (0) 2020.07.09 c++ array 배열 초기화 하는 방법 (2) 2020.07.03