Records rather than Memories

[C++] STL sort() 함수 다루기 본문

Software/C

[C++] STL sort() 함수 다루기

Downer 2019. 11. 30. 16:30

특정한 데이터를 정렬하기 위해 선택정렬, 삽입정렬, 퀵정렬, 합병정렬 등 여러가지 알고리즘을 만들어 정렬할 수 있는데 사실 실제로 정렬을 수행한다고 하면 이미 구현된 정렬 라이브러리를 사용하면 된다.

 

하지만 이러한 정렬에 대한 명확한 이해 없이 무작정 라이브러리를 가져다 쓰는 것은 좋지 않으므로 앞서 정렬 알고리즘에 대한 이해가 필요한 것이다.

 

 

- sort() 함수의 기본 사용법

 

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostrea>
#include <algorithm>
 
using namespace std;
 
int main(void) {
    int a[10= {27118310196};
    sort(a, a + 10);
    for(int i = 0; i < 10; i++) {
        cout << a[i] < ' ';
    }
 
}
cs

* 정렬할 기준을 사용자가 정의할 수 있다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostrea>
#include <algorithm>
 
using namespace std;
 
//내림차순으로 
bool compare(int a, int b) {
    return a > b;
}
 
int main(void) {
    int a[10= {27118310196};
    sort(a, a + 10, compare);
    for(int i = 0; i < 10; i++) {
        cout << a[i] < ' ';
    }
 
}
cs

 

- 데이터를 묶어서 정렬하는 법

기본적으로 단순 데이터를 정렬하는 것은 프로그래밍 대회에서 문제로 나올 법한 내용이다. 사실 실무에서 프로그래밍 할 때는 데이터들이 객체로 정리되어있기 때문에 가장 중요한 정렬 방식은 특정한 변수를 기준으로 정렬하는 것이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostrea>
#include <algorithm>
 
using namespace std;
 
class Item {
public:
    string name;
    int grade;
    Student(string name, int grade) {
        this->name = name;
        this->grade = grade;
    }
    // 정렬기준은 등급이 낮은 순서
    bool operator <(Item &item) {
        return this->grade < item.grade;
    }
};
 
int main(void) {
    Item item[] = {
    Item("천 갑옷"1),
    Item("강철 갑옷"3),
    Item("수정 갑옷"4),
    Item("낡은 쇠 갑옷"2),
    Item("용 갑옷"7)
 
    };
 
    sort(item, item + 5);
    for(int i = 0; i < 5; i++){
        cout << item[i].name << ' ';
    }
}
cs

 

 

 

Comments