반응형

알고리즘이 사용하는 정책 변경 방법

  • 일반 함수 사용
  • 함수 객체 사용 - <functional>
  • 람다 표현식 사용(C++11)
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional> // STL 함수 객체

bool cmp(int a, int b) { return a > b; }
int main()
{
    std::vector<int> v = { 1,2,3,4,5,6,7,8,9,10 };

    // 1. 일반 함수 사용.
    //std::sort(v.begin(), v.end(), cmp);

    // 2. 함수 객체
    std::greater<int> g; //>
    std::sort(v.begin(), v.end(), g);

    // 3. 람다 함수 사용, Lambda Expression C++11
    std::sort(v.begin(), v.end(),
        [](int a, int b) { return a > b; }); // [] lambda introducer

    for (auto& n : v)
    {
        std::cout << n << ", ";
    }
}

컨테이너가 사용하는 정책 변경 방법

#include <iostream>
#include <set>
#include <functional> // STL 함수 객체

int main()
{
    std::set<int, std::greater<int>> s; // tree, 컨테이너의 기본값 less<int> 대신 std::greater 사용

    s.insert(10);
    s.insert(30);
    s.insert(20);

    for (auto& n : s)
    {
        std::cout << n << ", ";
    }

}
반응형

'프로그래밍 언어 > C++' 카테고리의 다른 글

C++ 상속(Inheritance)  (0) 2019.05.12
C++ STL 정리  (0) 2019.05.12
C++ STL 알고리즘(Algorithm)  (0) 2019.05.12
C++ STL 반복자(iterator)  (0) 2019.05.12
C++ STL 컨테이너(Container)  (0) 2019.05.11

+ Recent posts