728x90
728x170
std::sort
default (1) | template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
|
---|---|
custom (2) | template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp); |
Sort elements in range
[first,last)
into ascending order.The elements are compared using
operator<
for the first version, and comp for the second.Equivalent elements are not guaranteed to keep their original relative order (see stable_sort).
Parameters
- first, last
- Random-access iterators to the initial and final positions of the sequence to be sorted. The range used is
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
RandomAccessIterator shall point to a type for which swap is properly defined and which is both move-constructibleand move-assignable. - comp
- Binary function that accepts two elements in the range as arguments, and returns a value convertible to
bool
. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
Algorithm 헤더에 있는 sort() 함수를 이용하여 오름차순 또는 내림차순 정렬을 쉽게 할 수 있다.
하지만 정렬 기준(comp)을 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 | #include <iostream> #include <algorithm> #include <string> using namespace std; #define N 100 bool Comp(string a, string b) { return a.length() > b.length(); // 내림차순 정렬 } int main() { string ip[N]; int num; cin >> num; cin.ignore(); for (int i = 0; i < num; i++) { getline(cin, ip[i]); } sort(ip, ip + num, Comp); for (int i = 0; i < num; i++) { cout << ip[i] << endl; } return 0; } |
[입력]
10 ten eleven hello nicetomeetyou example hi yellow green apple republicofkorea |
[출력]
republicofkorea nicetomeetyou example eleven yellow hello green apple ten hi |
오름차순으로 정렬을 하기 위해서는 Comp 함수의 return값을 a.length() < b.length();로 바꾸어 주면 된다.
728x90
그리드형(광고전용)
'Programming > C++' 카테고리의 다른 글
scanf() 입력 버퍼 비우는 방법 (0) | 2020.10.25 |
---|---|
Dynamic Memory (동적 메모리) (0) | 2019.05.06 |
Pointers (포인터) (0) | 2019.05.06 |
Naming Rules for Variables (변수 이름 생성 규칙) (0) | 2019.05.06 |
랜덤 함수/난수 생성 함수 (Random Function) (0) | 2018.10.07 |
입력된 문자열에서 공백을 제거하여 출력하기 (0) | 2018.09.24 |
Pair Vector (0) | 2017.11.26 |
[header][container] queue : priority_queue (0) | 2017.11.17 |