Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 코로나19
- it's a good thing
- counldn't have
- 형변환
- know
- java
- 명절 표현
- ISTQB
- C++
- html
- 제5인격
- gameQA
- 게임QA
- 명세기반테스트
- relif
- might have p.p
- keep -ing
- if조건절
- sort함수
- for ing
- happen to
- end up ing
- metascore
- 변수
- I'm glad
- by until
- continue to
- UE4
- Realtime Rendering
- by any chance
Archives
- Today
- Total
Records rather than Memories
[C++] STL sort() 함수 다루기 본문
특정한 데이터를 정렬하기 위해 선택정렬, 삽입정렬, 퀵정렬, 합병정렬 등 여러가지 알고리즘을 만들어 정렬할 수 있는데 사실 실제로 정렬을 수행한다고 하면 이미 구현된 정렬 라이브러리를 사용하면 된다.
하지만 이러한 정렬에 대한 명확한 이해 없이 무작정 라이브러리를 가져다 쓰는 것은 좋지 않으므로 앞서 정렬 알고리즘에 대한 이해가 필요한 것이다.
- 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] = {2, 7, 11, 8, 3, 10, 1, 9, 6};
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] = {2, 7, 11, 8, 3, 10, 1, 9, 6};
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 |
'Software > C' 카테고리의 다른 글
다이나믹 프로그래밍(Dynamic Programming) (0) | 2019.12.02 |
---|---|
C++ STL sort()함수 다루기 2 (0) | 2019.12.01 |
합집합 찾기(Union-Find) (0) | 2019.11.28 |
크루스칼 알고리즘(Kruskal Algorithm) (0) | 2019.11.28 |
최소 비용 신장 트리(MST, Minimum Spanning Tree)란 (0) | 2019.11.26 |
Comments