⌨️CS-STUDY/C++

[C++][header][algorithm] min max

미르의 블로그 2023. 2. 22. 01:56
728x90
반응형
『목차』
0. 설명에 앞서
1. Default Constructor
2. Custom Constructor 
3. Initializer List Constructor

0. std::min & std::max 설명에 앞서

참고

1. ①비교할 값들이 많거나②ArrayㆍVector와 같은 일련의 컨테이너에 저장되어 있다면, 최소값ㆍ최대값을 구하기 위해 min_element 또는 max_element 함수를 사용할 수 있다. (해당 함수에 대해서는 나중에 포스팅 하겠다.)

 

2. std::min와 std::max는 algorithm 라이브러리에 3가지 형태로 존재한다. 『① Default Constructor 』 『② Custom Constructor 』 『③ Initializer List Constructor 』 가 이에 해당한다.

반응형

1. std::min & std::max 『① Default Constructor 』

함수 원형
/* -- Default Constructor -- */
#include <algorithm> // min max 함수는 algorithm 라이브러리에 구현되어 있다.

/* min */
template <class T>
const T& min (const T& a, const T& b);

/* max */
template <class T>
const T& max (const T& a, const T& b);
반환 값
/* min */
std::min(a, b);

/* max */
std::max(a, b);

min : a값과 b값을 비교하여, 작은값을 반환하는 함수.

max : a값과 b값을 비교하여, 을 반환하는 함수.

3개 이상의 값 비교 방법
/* min */
std::min(a, b);			// a, b 중 최소값 반환.
std::min({a, b, c});		// a, b, c 중 최소값 반환.
std::min({a, b, c, d});		// a, b, c, d 중 최소값 반환.
std::min({a, b, c, d, e}); 	// a, b, c, d, e 중 최소값 반환.
...

/* max */
std::max(a, b); 		// a, b 중 최대값 반환.
std::max({a, b, c}); 		// a, b, c 중 최대값 반환.
std::max({a, b, c, d}); 	// a, b, c, d 중 최대값 반환.
std::max({a, b, c, d, e}); 	// a, b, c, d, e 중 최대값 반환.
...

{ }를 이용하여, 3개 이상의 값들에 대하여 최소값ㆍ최대값을 구할 수 있다. (이는 사실, 『③ Initializer List Constructor 』를 이용한 방법이다.)

객체(클래스)를 인자로 전달하는 방법 : operator< 이용
/* Input */
#include<iostream>
#include<algorithm>
using namespace std;

class Animal {
private:
    int age;    //나이
    int legs;   //다리 개수

public:
    Animal(int age, int legs) : age(age), legs(legs) {};

    //나이가 적은지 확인하고, 나이가 같다면 다리개수가 적은지 판단.
    bool operator<(const Animal& animal) const
    {
        if (age != animal.age)
            return age < animal.age;
        else
            return legs < animal.legs;
    }

    //cout 출력을 위한 "<<" 재정의.
    friend ostream& operator<<(ostream& os, const Animal& animal);
};

ostream& operator<<(ostream& os, const Animal& animal) {
    os << animal.age << '/' << animal.legs;
    return os;
}

int main(void) {
    cout << "고양이와 닭을 비교" << endl << endl;
    Animal cat1(10, 4);
    Animal cat2(20, 4);
    Animal chicken1(15, 2);
    Animal chicken2(20, 2);

    cout << "min(cat1(10,4),     cat2(20,4)) : " << min(cat1,     cat2) << endl;
    cout << "min(cat1(10,4), chicken1(15,2)) : " << min(cat1, chicken1) << endl;
    cout << "min(chicken2(20,2), cat1(10,4)) : " << min(chicken2, cat1) << endl;
    cout << "min(cat2(20,4), chicken2(20,2)) : " << min(cat2, chicken2) << endl << endl;

    cout << "max(cat1(10,4),     cat2(20,4)) : " << max(cat1,     cat2) << endl;
    cout << "max(cat1(10,4), chicken1(15,2)) : " << max(cat1, chicken1) << endl;
    cout << "max(chicken2(20,2), cat1(10,4)) : " << max(chicken2, cat1) << endl;
    cout << "max(cat2(20,4), chicken2(20,2)) : " << max(cat2, chicken2) << endl;

    return 0;
}
/* Output */
고양이와 닭을 비교

min(cat1(10,4),     cat2(20,4)) : 10/4
min(cat1(10,4), chicken1(15,2)) : 10/4
min(chicken2(20,2), cat1(10,4)) : 10/4
min(cat2(20,4), chicken2(20,2)) : 20/2

max(cat1(10,4),     cat2(20,4)) : 20/4
max(cat1(10,4), chicken1(15,2)) : 15/2
max(chicken2(20,2), cat1(10,4)) : 20/2
max(cat2(20,4), chicken2(20,2)) : 20/4

대소비교를 위한 operator< 가 클래스에 정의되어 있다면,  min max에 객체(클래스)를 집어넣어 사용할 수 있다.

예제

『예제1』

/* Input */
#include <iostream>
#include <algorithm>
using namespace std;

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

	return 0;
}
/* Output */
max(1, 2) == 2
min('a', 'z') == a
max(3.14, 2.73 == 3.14

『예제2』

/* Input */
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
	int a = 10, b = 30, c = 50, d = 20, e = 444;

	cout << a << ", " << e << "중 " << max(a, e) << "가 더 크다.\n";
	cout << b << ", " << c << ", " << d << "중 " << min({ b, c, d }) << "이 제일 작다.\n";

	pair<int, int> mm = minmax({ a, b, c, d, e });

	cout << a << ", " << b << ", " << c << ", " << d << ", " << e;
	cout << "중 가장 작은 값 = " << mm.first << "이며, 가장 큰 값 = " << mm.second << " 이다.\n";

	return 0;
}
/* Output */
10, 444444가 더 크다.
30, 50, 2020이 제일 작다.
10, 30, 50, 20, 444중 가장 작은 값 = 10이며, 가장 큰 값 = 444 이다.
반응형

2. std::min & std::max 『② Custom Constructor

함수 원형
/* -- Custom Constructor -- */
#include <algorithm> // min max 함수는 algorithm 라이브러리에 구현되어 있다.

/* min */
template <class T, class Compare>
const T& min (const T& a, const T& b, Compare comp);

/* max */
template <class T, class Compare>
const T& max (const T& a, const T& b, Compare comp);
반환 값

Compare Class(Functor)를 이용하는 방법.

'Compare comp' 인자에 해당하는 Compare Class(Functor)를 만들어, 자신이 원하는 방식으로 대ㆍ소 비교를 진행한 후 값을 반환받을 수 있다.

 

Compare Function을 이용하는 방법.

'Compare comp' 인자에 해당하는 Compare Function을 만들어, 자신이 원하는 방식으로 대ㆍ소 비교를 진행한 후 값을 반환 받을 수 있다.

예제

『예제1』 : ① Compare Class(Functor)를 이용하는 방법.

/* ① Compare Class(Functor)를 이용하는 방법. */
/* Input */
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

class Student {
public:
	string name;
	int num;
	
public:
	Student(string name, int num) : name(name), num(num) {}
};

class compare_class_sl { // sl = small large
public:
	bool operator() (const Student& a, const Student& b) {
		return a.num < b.num;
	}
};

class compare_class_ls { // ls = large small
public:
	bool operator() (const Student& a, const Student& b) {
		return a.num > b.num;
	}
};

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

	/* 임시객체 생성을 통한 방식 : compare_class_sl() 및 compare_class_ls()를 임시객체로 넘겨준다. */
	cout << max(s1, s2, compare_class_sl()).name << ": " << max(s1, s2, compare_class_sl()).num << endl;
	cout << max(s1, s2, compare_class_ls()).name << ": " << max(s1, s2, compare_class_ls()).num << endl;
	cout << min(s1, s2, compare_class_sl()).name << ": " << min(s1, s2, compare_class_sl()).num << endl;
	cout << min(s1, s2, compare_class_ls()).name << ": " << min(s1, s2, compare_class_ls()).num << endl;
	cout << endl;

	/* 객체 생성을 통한 방식 */
	compare_class_sl _compare_class_sl;
	compare_class_ls _compare_class_ls;
	cout << max(s1, s2, _compare_class_sl).name << ": " << max(s1, s2, _compare_class_sl).num << endl;
	cout << max(s1, s2, _compare_class_ls).name << ": " << max(s1, s2, _compare_class_ls).num << endl;
	cout << min(s1, s2, _compare_class_sl).name << ": " << min(s1, s2, _compare_class_sl).num << endl;
	cout << min(s1, s2, _compare_class_ls).name << ": " << min(s1, s2, _compare_class_ls).num << endl;

	return 0;
}
/* Output */
Park: 2
Hong: 1
Hong: 1
Park: 2

Park: 2
Hong: 1
Hong: 1
Park: 2

『예제2』 : ② Compare Function을 이용하는 방법.

/* ② Compare Function을 이용하는 방법. */
/* Input */
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

class Student {
public:
	string name;
	int num;

public:
	Student(string name, int num) : name(name), num(num) {}
};

bool compare_function_sl (const Student& a, const Student& b) { // sl = small large
	return a.num < b.num;
}

bool compare_function_ls(const Student& a, const Student& b) { // ls = large small
	return a.num > b.num;
}

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

	cout << max(s1, s2, compare_function_sl).name << ": " << max(s1, s2, compare_function_sl).num << endl;
	cout << max(s1, s2, compare_function_ls).name << ": " << max(s1, s2, compare_function_ls).num << endl;
	cout << min(s1, s2, compare_function_sl).name << ": " << min(s1, s2, compare_function_sl).num << endl;
	cout << min(s1, s2, compare_function_ls).name << ": " << min(s1, s2, compare_function_ls).num << endl;

	return 0;
}
/* Output */
Park: 2
Hong: 1
Hong: 1
Park: 2
반응형

3. std::min & std::max 『③ Initializer List Constructor 

함수 원형
/* -- Initializer List Constructor -- */
#include <algorithm> // min max 함수는 algorithm 라이브러리에 구현되어 있다.

/* min */
template <class T> T max (initializer_list<T> il);
template <class T, class Compare>
T min (initializer_list<T> il, Compare comp); // Compare comp는 생략 가능.

/* max */
template <class T> T max (initializer_list<T> il);
template <class T, class Compare>
T max (initializer_list<T> il, Compare comp); // Compare comp는 생략 가능.
반환 값

initializer_list<T> il 에 해당하는 인자로 { }를 이용, 여러 값들을 묶어 전달하면, 해당 값들을 비교하여 max 혹은 min 값을 반환받는다. (Compare comp에 해당하는 인자는 생략 가능하다.)

예제
/* Input */
#include <iostream>
#include <algorithm>
using namespace std;

int main(void) {
	cout << min({ 2, 4, 6, 8, 10 }) << endl;
	cout << max({ 2, 4, 6, 8, 10 }) << endl;

	return 0;
}
/* Output */
2
10

 

728x90
반응형