카테고리 없음

[C++] sort 함수

검은젤리곰 2019. 7. 19. 18:14

sort 함수는 배열을 오름차순으로 정렬하는 함수이다.

사용 예는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <algorithm>
 
using namespace std;
 
void main(){
    int arr[5= {21453};
    sort(arr,arr+5);
}
 
cs

위 코드를 실행할 경우, 배열이 오름차순으로 정렬된다.

{2, 1, 4, 5, 3} -> {1, 2, 3, 4, 5}

함수 사용시, sort(시작 주소, 마지막 주소)의 형태로 입력하면 된다.

이를 이용해 한가지 간단한 프로그램을 만들어보았다.

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <algorithm>
#include <string>
#include <time.h>
 
using namespace std;
#define MAX 30000
#define MIN 60000
//유저를 점수에 맞추어 나열하자.
 
class player {
private:
    int score;
    string userName;
public:
    player(int inputScore, string inputName) {
        this->score = inputScore;
        this->userName = inputName;
    }
 
    bool operator< (player &player) {
        return this->score < player.score;
    }
    string printUserName() {
        return this->userName;
    }
    void print() {
        cout << this->userName << "의 점수는 " << this->score << "입니다." << endl;
    }
};
 
void main() {
 
    srand((unsigned int)time(NULL));
    player user[] = {
        player(MIN + rand() % MAX, "젤리곰"), 
        player(MIN + rand() % MAX, "연어훈제하는불곰"),
        player(MIN + rand() % MAX, "렌"), 
        player(MIN + rand() % MAX,"마메"), 
        player(MIN + rand() % MAX, "하길")
    };
 
    for(int i=0;i<5;i++){
            user[i].print();
    }
 
    sort(user, user + 5);
 
    cout << "========== 순위표 ==========" << endl;
 
    for (int i = 0; i <5; i++) {
        cout << i + 1 << "위는 " << user[i].printUserName() << endl;
    }
    cout << "이번 달 클랜장은 " << user[0].printUserName() << "입니다." << endl;
    system("pause");
}
cs
 

점수와 유저네임을 메소드로 가지고있는 클래스를 생성하고, 각 유저들의 점수에 따라 순위를 출력하도록 했다.

bool operator< (player &player) {

        return this->score < player.score;

    }

연산자 오버라이딩을 사용해 "<" 연산자를 다음과 같이 처리하겠다는 의미를 가지게 했다.