새소식

언어/C++

c++ std::max, min 함수 정리

  • -

c++11을 기준으로 다음 사이트를 참고하여 작성되었습니다
max와 min은 algorithm 라이브러리에 존재합니다.

형태는 총 3가지가 존재합니다

max

constructor

1. default constructor

형태는 다음과 같습니다

template <class T> const T& max (const T& a, const T& b);

예제

int main() {
    cout << "max(1,2)==" << max(1,2) << endl;    // max(1,2)==2
    cout << "max('a', 'z')==" << max('a', 'z') << endl;    // max('a', 'z')==z
    cout << "max(3.14, 2.73)==" << max(3.14, 2.73) << endl;    // max(3.14, 2.73)==3.14
}

위 처럼 두 파라미터를 넣어 더 큰 숫자를 얻어낼 수 있습니다

2. custom constructor

형태는 다음과 같습니다

template <class T, class Compare>
  const T& max (const T& a, const T& b, Compare comp);

Compare를 만들어서 자기가 원하는 Compare를 만들어서 비교할 수 있습니다.

예제

class Student {
public:
    string name;
    int num;

    Student(string name, int num) {
        this->name = name;
        this->num = num;
    }
};

class customcompare {
public:
    bool operator() (const Student& a, const Student& b) {
        if (a.num < b.num) {
            return true;
        }
        return false;
    }
};

int main()
{
    Student s1("Hong", 1);
    Student s2("Park", 2);

    customcompare cmp;
    Student max_student = max(s1, s2, cmp);
    cout << max_student.name << ": " << max_student.num;

    return 0;
}

3. initializer list contructor

형태는 다음과 같습니다
이는 2번과 비슷하지만 비교할 수에 list를 넣어서 여러 값들 중에서 비교하여 가장 큰 값을 뽑아낼 수 있습니다
아래 형태 말고 Compare 값을 넣지 않고 list만 넣어서 max 값을 구할 수도 있습니다.

template <class T> T max (initializer_list<T> il);
template <class T, class Compare>
  T max (initializer_list<T> il, Compare comp);

예제

int main() {
    cout << max({1, 10, 50, 200}) << endl;
}

min

min도 max와 형태가 같으므로 생략하겠습니다.

예제

cout << min(1,2) << endl;
cout << min({1,2,3}) << endl;
cout << min('a', 'z') << endl;
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.