귀염둥이의 메모

[C++] sort 이용한 오름차순, 내림차순 정렬, greater<>, less<> 본문

CS/C, C++

[C++] sort 이용한 오름차순, 내림차순 정렬, greater<>, less<>

겸둥이xz 2021. 6. 21. 14:12
반응형

sort() - 기본 오름차순

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {

    vector<int> v = {3, 2, 0, 9, 7, 1, 4, 8, 6};
    sort(v.begin(), v.end());
    for (int n : v) {
        cout << n << ' ';
    }
    cout << '\n';
    return 0;
}

// 0 1 2 3 4 6 7 8 9

sort() + std::less<> - 오름차순

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {

    vector<int> v = {3, 2, 0, 9, 7, 1, 4, 8, 6};
    sort(v.begin(), v.end(), less<int>());
    for (int n : v) {
        cout << n << ' ';
    }
    cout << '\n';
    return 0;
}

// 0 1 2 3 4 6 7 8 9 

sort() + std::greater<> - 내림차순

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {

    vector<int> v = {3, 2, 0, 9, 7, 1, 4, 8, 6};
    sort(v.begin(), v.end(), greater<int>());
    for (int n : v) {
        cout << n << ' ';
    }
    cout << '\n';
    return 0;
}

// 9 8 7 6 4 3 2 1 0 
반응형

'CS > C, C++' 카테고리의 다른 글

[C++] STL (Standard Template Library)  (0) 2021.02.17
[C언어] 포인터(Pointer)  (0) 2021.02.09
[C++] std::accumulate  (0) 2021.02.08
Comments