ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1067)
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (180)
      • Unreal (69)
      • Unity (100)
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (235)
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (55)
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (346)
      • C++ (167)
      • C# (88)
      • Java (9)
      • Python (33)
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (9)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 함수
  • 오블완
  • C
  • SQL
  • 배열
  • Unity
  • 클래스
  • 티스토리챌린지
  • c#
  • 프로그래머스
  • 언리얼
  • string
  • 백준
  • C++
  • 문자열
  • 알고리즘
  • 유니티
  • 그래픽스
  • 파이썬
  • 포인터

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

프로그래밍 언어/C++

[C++] min max 함수 (algorithm 라이브러리)

2023. 9. 6. 16:25

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);

 

3개 이상의 값 비교 방법

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

/* 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 중 최대값 반환.
...

 

객체(클래스)를 인자로 전달하는 방법 : operator< 이용

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

/* 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

 

예제 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, 444중 444가 더 크다.
30, 50, 20중 20이 제일 작다.
10, 30, 50, 20, 444중 가장 작은 값 = 10이며, 가장 큰 값 = 444 이다.

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

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

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

 

② Compare Function을 이용하는 방법.

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

/* -- 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);

 

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

/* -- 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는 생략 가능.

 

예제

/* 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

 

[C++][header][algorithm] min max (tistory.com)

저작자표시 (새창열림)

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

[C] 서식 지정자의 모든것 (서식문자)  (0) 2023.09.09
[C] 피보나치 수열과 메모이제이션  (0) 2023.09.09
[C] min max 매크로함수  (0) 2023.09.06
[C] 문자열에서 공백을 제거하는 함수  (0) 2023.09.05
[C] 재귀함수(Recursive/리쿼시브)의 개념과 공부하는 이유  (0) 2023.09.05
    '프로그래밍 언어/C++' 카테고리의 다른 글
    • [C] 서식 지정자의 모든것 (서식문자)
    • [C] 피보나치 수열과 메모이제이션
    • [C] min max 매크로함수
    • [C] 문자열에서 공백을 제거하는 함수
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바